FiveTech Support Forums

FiveWin / Harbour / xBase community
Board index FiveWin for Harbour/xHarbour Webview question
Posts: 1818
Joined: Wed Oct 26, 2005 02:49 PM

Re: Webview question

Posted: Sun Jul 02, 2023 05:14 PM
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 (fw): Select all Collapse
#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

[ Turbo Incremental Link64 6.98 Embarcadero 7.70 ] [ FiveWin 25.01 ] [ xHarbour 64 bits) ]
Posts: 1818
Joined: Wed Oct 26, 2005 02:49 PM

Re: Webview question

Posted: Sun Jul 02, 2023 05:49 PM
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

[ Turbo Incremental Link64 6.98 Embarcadero 7.70 ] [ FiveWin 25.01 ] [ xHarbour 64 bits) ]
Posts: 44162
Joined: Thu Oct 06, 2005 05:47 PM

Re: Webview question

Posted: Sun Jul 02, 2023 08:17 PM
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
Posts: 6755
Joined: Wed Feb 15, 2012 08:25 PM

Re: Webview question

Posted: Sun Jul 02, 2023 09:50 PM

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
Posts: 44162
Joined: Thu Oct 06, 2005 05:47 PM

Re: Webview question

Posted: Mon Jul 03, 2023 06:27 AM
Estimado Leandro,

Resuelto! :-)

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

Ya lo teniamos, pero lo olvidé :-)

Aqui tienes un ejemplo:
Code (fw): Select all Collapse
// 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
Posts: 44162
Joined: Thu Oct 06, 2005 05:47 PM

Re: Webview question

Posted: Mon Jul 03, 2023 07:45 AM
oWebView:Return() se usa para devolver un valor desde el oWebView:bOnBind

Nuevo ejemplo webviewuni2.prg
Code (fw): Select all Collapse
#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 (fw): Select all Collapse
   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
Posts: 6984
Joined: Fri Oct 07, 2005 07:07 PM

Re: Webview question

Posted: Mon Jul 03, 2023 11:03 AM

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

Posts: 44162
Joined: Thu Oct 06, 2005 05:47 PM

Re: Webview question

Posted: Mon Jul 03, 2023 11:53 AM

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
Posts: 44162
Joined: Thu Oct 06, 2005 05:47 PM

Re: Webview question

Posted: Mon Jul 03, 2023 12:19 PM
New example webviewbody.prg
Code (fw): Select all Collapse
// 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
Posts: 1818
Joined: Wed Oct 26, 2005 02:49 PM

Re: Webview question

Posted: Mon Jul 03, 2023 03:59 PM
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

[ Turbo Incremental Link64 6.98 Embarcadero 7.70 ] [ FiveWin 25.01 ] [ xHarbour 64 bits) ]
Posts: 6984
Joined: Fri Oct 07, 2005 07:07 PM

Re: Webview question

Posted: Mon Jul 03, 2023 05:44 PM
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

Posts: 6984
Joined: Fri Oct 07, 2005 07:07 PM

Re: Webview question

Posted: Mon Jul 03, 2023 09:28 PM

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

Posts: 44162
Joined: Thu Oct 06, 2005 05:47 PM

Re: Webview question

Posted: Tue Jul 04, 2023 03:12 AM
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 (fw): Select all Collapse
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
Posts: 44162
Joined: Thu Oct 06, 2005 05:47 PM

Re: Webview question

Posted: Tue Jul 04, 2023 03:14 AM
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
Posts: 6984
Joined: Fri Oct 07, 2005 07:07 PM

Re: Webview question

Posted: Tue Jul 04, 2023 06:26 AM
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