Webview question

User avatar
leandro
Posts: 1688
Joined: Wed Oct 26, 2005 2:49 pm
Location: Colombia
Contact:

Re: Webview question

Post by leandro »

Antonio buenos días como estas?

Logramos montar un ejemplo para poder validar el acceso de los usuarios a la aplicación, podemos recoger la variables desde el navegador y enviarlas a FW para que se haga el proceso de validación mediante una dbf. Aunque ya es funcional, ahora nos gustaría poder enviar información al navegador desde FW, por ejemplo, mostrar un alert desde el navegador, informando que el usuario no esta registrado o la contraseña esta mal. No mediante un msginfo() directo desde fw como esta en el ejemplo.

Espero haberme hecho entender, de antemano gracias

Mirar al final de código

webviewval.prg

Code: Select all | Expand

#include "FiveWin.ch"

//----------------------------------------------------------------------------//

function Main()
    local oWebView := TWebView():New()
    local aEstru := {   { "user","C",10,0 },;
                    { "pass","C",10,0 },;
                    { "acti","L", 1,0 } }

    public d_user

    IF !FILE (".\usuarios.dbf")
        FERASE(".\usuarios.dbf")
    ENDIF
    
    DbCreate( ".\usuarios.dbf", aEstru )
    
    USE ".\usuarios.dbf" ALIAS d_user NEW EXCLUSIVE 
    SELECT d_user
    dbappend()
    d_user->user := "root"
    d_user->pass := "123"
    d_user->acti := .T.

    oWebView:bOnBind = { | cJson, nCalls | validating( cJson, nCalls ) }
    oWebView:Bind( "SendToFWH" )
    oWebView:Navigate( Html() )
    oWebView:SetTitle( "Validando formulario" )
    Sleep( 200 )
    oWebView:Run()
    oWebView:Destroy()
    
    
    d_user->(DbCloseArea())

return nil

//----------------------------------------------------------------------------//

function Html()

   local cHtml
   
   TEXT INTO cHtml
      data:text/html,
      <html>
         <head>
         </head>
         <body style="background-color:cyan">
            <h2>Validando Formulario</h2>
            <small><strong>Usuario</strong></small>
            <br>
            <input type="text" id="txt_user" placeholder="root"></input>
            <br>
            <small id="sml_user"></small>
            <br>
            <small><strong>Contraseña</strong></small>
            <br>
            <input type="password" id="txt_pass" placeholder="123"></input>
            <br>
            <small id="sml_pass"></small>
            <br>
            <button onclick="validateInfo();" id="btn_val">Ingresar</button>

         </body>
      </html>
    <script>
    function validateInfo(){
        var aError = new Array();
        if(document.getElementById("txt_pass").value==""){
            document.getElementById("sml_pass").innerHTML = "Ingrese contraseña";
            aError.push("Error usuario");
        }else{
            document.getElementById("sml_pass").innerHTML = "";
        }
        if(document.getElementById("txt_user").value==""){
            document.getElementById("sml_user").innerHTML = "Ingrese usuario";
            aError.push("Error usuario");
        }else{
            document.getElementById("sml_user").innerHTML = "";
        }
        if(aError.length==0){
            var cUse = document.getElementById("txt_user").value;
            var cPas = document.getElementById("txt_pass").value;
            document.getElementById("btn_val").setAttribute("onclick", "SendToFWH( '"+cUse+"','"+cPas+"' );");
            document.getElementById("btn_val").click();
            document.getElementById("btn_val").setAttribute("onclick", "validateInfo();");
        }
    }
    </script>     
      
   ENDTEXT     

return cHtml


function validating(cJson, nCalls)
Local hRspn := hash()
hb_jsondecode(cJson ,@hRspn ) 

SELECT d_user 
Dbgotop()
locate for alltrim(d_user->user)=alltrim(hRspn[1]) .AND. alltrim(d_user->pass)=alltrim(hRspn[2])
if found()
    msginfo("ingreso correcto")
else
    msginfo("usuario o contraseña errados") //LA IDEA ES ENVIAR ESTE ERROR AL NAVEGADOR PARA QUE MUESTRE MEDIANTE UN ALERT
endif
return nil 

//----------------------------------------------------------------------------//
 
Saludos
LEANDRO AREVALO
Bogotá (Colombia)
https://hymlyma.com
https://hymplus.com/
leandroalfonso111@gmail.com
leandroalfonso111@hotmail.com

[ Embarcadero C++ 7.60 for Win32 ] [ FiveWin 23.07 ] [ xHarbour 1.3.0 Intl. (SimpLex) (Build 20230914) ]
User avatar
leandro
Posts: 1688
Joined: Wed Oct 26, 2005 2:49 pm
Location: Colombia
Contact:

Re: Webview question

Post by leandro »

Interestingly, the syntax used in the webview3.prg example does not show the ghost window. Specifically, assigning the dialog/window handle when calling the Webview:New() method.

oWebView := TWebView():New( , oDlg:hWnd )
Gracias por el dato :D
Saludos
LEANDRO AREVALO
Bogotá (Colombia)
https://hymlyma.com
https://hymplus.com/
leandroalfonso111@gmail.com
leandroalfonso111@hotmail.com

[ Embarcadero C++ 7.60 for Win32 ] [ FiveWin 23.07 ] [ xHarbour 1.3.0 Intl. (SimpLex) (Build 20230914) ]
User avatar
Antonio Linares
Site Admin
Posts: 42259
Joined: Thu Oct 06, 2005 5:47 pm
Location: Spain
Contact:

Re: Webview question

Post by Antonio Linares »

Estimado Leandro,

chatGPT dice que podemos hacerlo asi:
webView2.CoreWebView2.ExecuteScriptAsync(javascriptFunctionName);
Asi que he abierto un nuevo issue en github.com/webview/webview y veamos lo que Steffen responde:
https://github.com/webview/webview/issues/945
regards, saludos

Antonio Linares
www.fivetechsoft.com
User avatar
cnavarro
Posts: 6552
Joined: Wed Feb 15, 2012 8:25 pm
Location: España

Re: Webview question

Post by cnavarro »

Para eso es para lo que existe WebView_Return
Cristobal Navarro
Hay dos tipos de personas: las que te hacen perder el tiempo y las que te hacen perder la noción del tiempo
El secreto de la felicidad no está en hacer lo que te gusta, sino en que te guste lo que haces
User avatar
Antonio Linares
Site Admin
Posts: 42259
Joined: Thu Oct 06, 2005 5:47 pm
Location: Spain
Contact:

Re: Webview question

Post by Antonio Linares »

Estimado Leandro,

Resuelto! :-)

oWebView:Eval( "alert( 'from javascript' )" )

Ya lo teniamos, pero lo olvidé :-)

Aqui tienes un ejemplo:

Code: Select all | Expand

// Please install https://developer.microsoft.com/en-us/microsoft-edge/webview2/ x86 version before using it

#include "FiveWin.ch"

static oWebView

function Main()

   local oWnd

   DEFINE WINDOW oWnd TITLE "Using a webview from an existing window" MENU BuildMenu()

   oWnd:Center()
   oWebView = TWebView():New()
   owebView:SetParent( oWnd )

   oWebView:Navigate( "http://www.google.com" )
   oWebView:SetUserAgent( "Mozilla/5.0 (Linux; Android 6.0; Nexus 5 Build/MRA58N) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/103.0.5060.53 Mobile Safari/537.36" )

   ACTIVATE WINDOW oWnd CENTER ;
      ON RESIZE SetWindowPos( oWebView:GetWindow(), 0, 20, 20, oWnd:nWidth - 40, oWnd:nHeight - 40 )

   oWebView:Destroy()

return nil

function BuildMenu()

   local oMenu

   MENU oMenu 
      MENUITEM "Eval ." ACTION oWebView:Eval( "alert( 'from javascript' )" )
      MENUITEM "About ." ACTION MsgAbout()
   ENDMENU
   
return oMenu  
regards, saludos

Antonio Linares
www.fivetechsoft.com
User avatar
Antonio Linares
Site Admin
Posts: 42259
Joined: Thu Oct 06, 2005 5:47 pm
Location: Spain
Contact:

Re: Webview question

Post by Antonio Linares »

oWebView:Return() se usa para devolver un valor desde el oWebView:bOnBind

Nuevo ejemplo webviewuni2.prg

Code: Select all | Expand

#include "FiveWin.ch"

//----------------------------------------------------------------------------//

function Main()

   local oWebView := TWebView():New()

   oWebView:Center() 
   oWebView:bOnBind = { | cJson, cCalls | MsgInfo( cJson, cCalls ),;
                        oWebView:Return( cCalls, 0, "{ 'result': 'Hello from PRG' }" ) }
   oWebView:Bind( "SendToFWH" )
   oWebView:Navigate( Html() )
   Sleep( 200 )
   oWebView:Run()
   oWebView:Destroy()

return nil

//----------------------------------------------------------------------------//

function Html()

   local cHtml

   TEXT INTO cHtml
      data:text/html,
      <head><body> 
      <button id='btn-test' >Click Me</button>
      <script> 
      function test(evt) {  
          var someData = { 'param1': 'Hello from JS' };  
          var s = SendToFWH( evt.target.id, evt.type, someData ) 
          .then(s => {  
              alert(s.result);  
          })  
      }  
      document.getElementById('btn-test').addEventListener('click', test);  
      </script>
      </head></body>
   ENDTEXT      

return cHtml

//----------------------------------------------------------------------------//
En la clase TWebView() es preciso añadir este nuevo método:

Code: Select all | Expand

   METHOD Return( cRequest, nBindResult, cFromPrgToJS ) INLINE ;
      WebView_Return( ::hWebView, cRequest, nBindResult, cFromPrgToJS )
nBindResult debe ser cero para indicar que no hay error y 1 para indicar error
regards, saludos

Antonio Linares
www.fivetechsoft.com
User avatar
Otto
Posts: 6378
Joined: Fri Oct 07, 2005 7:07 pm
Contact:

Re: Webview question

Post by Otto »

Dear Antonio,

Thank you so much for your work. I greatly appreciate it. Is there somewhere I can download the entire FIVEWIN Update?

Best regards,
Otto
********************************************************************
mod harbour - Vamos a la conquista de la Web
modharbour.org
https://www.facebook.com/groups/modharbour.club
********************************************************************
User avatar
Antonio Linares
Site Admin
Posts: 42259
Joined: Thu Oct 06, 2005 5:47 pm
Location: Spain
Contact:

Re: Webview question

Post by Antonio Linares »

Dear Otto,

We have just published a new FWH 23.04 build 2

Please download it as usual

many thanks
regards, saludos

Antonio Linares
www.fivetechsoft.com
User avatar
Antonio Linares
Site Admin
Posts: 42259
Joined: Thu Oct 06, 2005 5:47 pm
Location: Spain
Contact:

Re: Webview question

Post by Antonio Linares »

New example webviewbody.prg

Code: Select all | Expand

// Please install https://developer.microsoft.com/en-us/microsoft-edge/webview2/ x86 version before using it

#include "FiveWin.ch"

static oWebView

function Main()

   local oWnd

   DEFINE WINDOW oWnd TITLE "Using a webview from an existing window" MENU BuildMenu()

   oWnd:Center()
   oWebView = TWebView():New()
   owebView:SetParent( oWnd )

   oWebView:Navigate( "http://www.google.com" )
   oWebView:SetUserAgent( "Mozilla/5.0 (Linux; Android 6.0; Nexus 5 Build/MRA58N) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/103.0.5060.53 Mobile Safari/537.36" )
   oWebView:Bind( "SendToFWH" )
   oWebView:bOnBind = { | cJson, cCalls | MsgInfo( cJson ) }

   ACTIVATE WINDOW oWnd CENTER ;
      ON RESIZE SetWindowPos( oWebView:GetWindow(), 0, 20, 20, oWnd:nWidth - 40, oWnd:nHeight - 40 )

   oWebView:Destroy()

return nil

function BuildMenu()

   local oMenu

   MENU oMenu 
      MENUITEM "Eval ." ACTION oWebView:Eval( "SendToFWH( document.body.outerHTML )" )
      MENUITEM "About ." ACTION MsgAbout()
   ENDMENU
   
return oMenu  
regards, saludos

Antonio Linares
www.fivetechsoft.com
User avatar
leandro
Posts: 1688
Joined: Wed Oct 26, 2005 2:49 pm
Location: Colombia
Contact:

Re: Webview question

Post by leandro »

Excelente Antonio, muchas gracias por el ejemplo :D, hace lo que queremos.
oWebView:Eval( "alert( 'from javascript' )" )
Por otro lado, será que nos puedes actualizar las lib para xharbour 2304 y enviármelas, con el cambio de clase que acabas de hacer :oops: , para revisar el compartemiento de webview.return(). De paso si nos puedes explicar cual es la diferencia entre los dos métodos, y en que momento es mas conveniente usar uno u otro.

De antemano gracias
Saludos
LEANDRO AREVALO
Bogotá (Colombia)
https://hymlyma.com
https://hymplus.com/
leandroalfonso111@gmail.com
leandroalfonso111@hotmail.com

[ Embarcadero C++ 7.60 for Win32 ] [ FiveWin 23.07 ] [ xHarbour 1.3.0 Intl. (SimpLex) (Build 20230914) ]
User avatar
Otto
Posts: 6378
Joined: Fri Oct 07, 2005 7:07 pm
Contact:

Re: Webview question

Post by Otto »

Dear Antonio,

Thank you very much for the FTDN update. I have installed the new version, and it looks good.

I am also interested to know if it is now possible to exchange data between webview2 and Fivewin through a direct connection.

Kind regards,
Otto

Image
********************************************************************
mod harbour - Vamos a la conquista de la Web
modharbour.org
https://www.facebook.com/groups/modharbour.club
********************************************************************
User avatar
Otto
Posts: 6378
Joined: Fri Oct 07, 2005 7:07 pm
Contact:

Re: Webview question

Post by Otto »

Hello friends,

I have successfully implemented the functionality to return a JSON from JavaScript. Everything is working fine.
oWebView:bOnBind = { | cJson, cCalls |
hb_jsondecode(cJson, @hPost), xbrowse(hPost),
oWebView:Return(cCalls, 0, "{ 'result': 'Hello from PRG' }") }.

I believe that WebView2 provides me with more flexibility to work on the desktop. With it, we can develop screens using HTML/JS without the need for a web server.
Best regards,
Otto
********************************************************************
mod harbour - Vamos a la conquista de la Web
modharbour.org
https://www.facebook.com/groups/modharbour.club
********************************************************************
User avatar
Antonio Linares
Site Admin
Posts: 42259
Joined: Thu Oct 06, 2005 5:47 pm
Location: Spain
Contact:

Re: Webview question

Post by Antonio Linares »

New METHOD InjectJavascript( cScript ) CLASS TWebView by Charles KWON ( charleskwonohjun@gmail.com )

This allows you to add your own javascript code to public websites!!!

really powerful:

Code: Select all | Expand

METHOD InjectJavascript( cScript ) CLASS TWebView

   local cInjection := ""

   cInjection := "var script = document.createElement('script');" + CRLF
   cInjection += "script.textContent = `" + CRLF

   cInjection += cScript + CRLF

   cInjection += "`;" + CRLF
   cInjection += "document.head.appendChild(script);"

   ::Eval( cInjection )

return nil
regards, saludos

Antonio Linares
www.fivetechsoft.com
User avatar
Antonio Linares
Site Admin
Posts: 42259
Joined: Thu Oct 06, 2005 5:47 pm
Location: Spain
Contact:

Re: Webview question

Post by Antonio Linares »

Dear Otto,

> I believe that WebView2 provides me with more flexibility to work on the desktop. With it, we can develop screens using HTML/JS without the need for a web server

web and desktop working in better harmony :-)
regards, saludos

Antonio Linares
www.fivetechsoft.com
User avatar
Otto
Posts: 6378
Joined: Fri Oct 07, 2005 7:07 pm
Contact:

Re: Webview question

Post by Otto »

I send data from FIVEWIN/HARBOUR to the WebView2 control using the ADD button, modify the data, and send it back to Fivewin.
No web server needed

Image
********************************************************************
mod harbour - Vamos a la conquista de la Web
modharbour.org
https://www.facebook.com/groups/modharbour.club
********************************************************************
Post Reply