Jump to content

WebView2AutoIt - AutoIt WebView2 Component (COM Interop)


Recommended Posts

Posted (edited)
...
$g_iSetWidth = Default
$g_iMaxWidth = 400
$g_iSetHeight = Default
$g_iMaxHeight = 800
...
                Case StringInStr($sCmd, "/SetWidth:")
                    $g_iSetWidth = Int(StringReplace($sCmd, "/SetWidth:", ""))
                Case StringInStr($sCmd, "/SetHeight:")
                    $g_iSetHeight = Int(StringReplace($sCmd, "/SetHeight:", ""))

...
        ; Constraints
        If $iW > $g_iMaxWidth Then $iW = $g_iMaxWidth
        If $iH > $g_iMaxHeight Then $iH = $g_iMaxHeight
        If Not IsKeyword($g_iSetWidth) Then $iW = $g_iSetWidth
        If Not IsKeyword($g_iSetHeight) Then $iH = $g_iSetHeight
        If $iW < 150 Then $iW = 150
        If $iH < 50 Then $iH = 50
...

..that way if the user want to set the size for themselves, they can.

Edited by argumentum

Follow the link to my code contribution ( and other things too ).
FAQ - Please Read Before Posting  image.gif.922e3a93535f431de08b31ee669cc446.gif
autoit_scripter_blue_userbar.png

Posted

please post entire reproducer with comments in code

Signature beginning:
* Please remember: "AutoIt"..... *  Wondering who uses AutoIt and what it can be used for ? * Forum Rules *
* ADO.au3 UDF * POP3.au3 UDF * XML.au3 UDF * IE on Windows 11 * How to ask ChatGPT for AutoIt Code * for other useful stuff click the following button:

Spoiler

Any of my own code posted anywhere on the forum is available for use by others without any restriction of any kind. 

My contribution (my own projects): * Debenu Quick PDF Library - UDF * Debenu PDF Viewer SDK - UDF * Acrobat Reader - ActiveX Viewer * UDF for PDFCreator v1.x.x * XZip - UDF * AppCompatFlags UDF * CrowdinAPI UDF * _WinMergeCompare2Files() * _JavaExceptionAdd() * _IsBeta() * Writing DPI Awareness App - workaround * _AutoIt_RequiredVersion() * Chilkatsoft.au3 UDF * TeamViewer.au3 UDF * JavaManagement UDF * VIES over SOAP * WinSCP UDF * GHAPI UDF - modest begining - comunication with GitHub REST API * ErrorLog.au3 UDF - A logging Library * Include Dependency Tree (Tool for analyzing script relations) * Show_Macro_Values.au3 *

 

My contribution to others projects or UDF based on  others projects: * _sql.au3 UDF  * POP3.au3 UDF *  RTF Printer - UDF * XML.au3 UDF * ADO.au3 UDF * SMTP Mailer UDF * Dual Monitor resolution detection * * 2GUI on Dual Monitor System * _SciLexer.au3 UDF * SciTE - Lexer for console pane * 

Useful links: * Forum Rules * Forum etiquette *  Forum Information and FAQs * How to post code on the forum * AutoIt Online Documentation * AutoIt Online Beta Documentation * SciTE4AutoIt3 getting started * Convert text blocks to AutoIt code * Games made in Autoit * Programming related sites * Polish AutoIt Tutorial * DllCall Code Generator * 

Wiki: * Expand your knowledge - AutoIt Wiki * Collection of User Defined Functions * How to use HelpFile * Good coding practices in AutoIt * 

OpenOffice/LibreOffice/XLS Related: WriterDemo.au3 * XLS/MDB from scratch with ADOX

IE Related:  * How to use IE.au3  UDF with  AutoIt v3.3.14.x * Why isn't Autoit able to click a Javascript Dialog? * Clicking javascript button with no ID * IE document >> save as MHT file * IETab Switcher (by LarsJ ) * HTML Entities * _IEquerySelectorAll() (by uncommon) * IE in TaskScheduler * IE Embedded Control Versioning (use IE9+ and HTML5 in a GUI) * PDF Related: * How to get reference to PDF object embeded in IE * IE on Windows 11 * 

I encourage you to read: * Global Vars * Best Coding Practices * Please explain code used in Help file for several File functions * OOP-like approach in AutoIt * UDF-Spec Questions *  EXAMPLE: How To Catch ConsoleWrite() output to a file or to CMD *

I also encourage you to check awesome @trancexx code:  * Create COM objects from modules without any demand on user to register anything. * Another COM object registering stuff * OnHungApp handler * Avoid "AutoIt Error" message box in unknown errors  * HTML editor * 

winhttp.au3 related : * https://www.autoitscript.com/forum/topic/206771-winhttpau3-download-problem-youre-speaking-plain-http-to-an-ssl-enabled-server-port/

"Homo sum; humani nil a me alienum puto" - Publius Terentius Afer
"Program are meant to be read by humans and only incidentally for computers and execute" - Donald Knuth, "The Art of Computer Programming"
:naughty:  :ranting:, be  :) and       \\//_.

Anticipating Errors :  "Any program that accepts data from a user must include code to validate that data before sending it to the data store. You cannot rely on the data store, ...., or even your programming language to notify you of problems. You must check every byte entered by your users, making sure that data is the correct type for its field and that required fields are not empty."

Signature last update: 2023-04-24

Posted (edited)

Modern Sidebar UI

Injects a high-performance, Chromium-based Sidebar into a Win32 GUI using WebView2.
This method bypasses GDI/Win32 rendering limitations, allowing for full CSS3 animations, 
Vector (SVG) icons, and 100% Color Emoji support.

:D

260401-110615-022_AutoIt3_ZQxWS.gif

 

#include <GUIConstantsEx.au3>
#include <WindowsConstants.au3>
#include "NetWebView2Lib.au3"

Global $g_idMemo

_Example()

;---------------------------------------------------------------------------------------
Func _Example()
    Local $hGui = GUICreate("Modern Sidebar UI", 550, 410)
    GUISetBkColor(0x252526) ; Dark Background

    $g_idMemo = GUICtrlCreateEdit("", 160, 10, 370, 390, $WS_VSCROLL, 0)
    GUICtrlSetFont(-1, 11, 400, 0, "Courier New")
    GUICtrlSetColor(-1, 0xF0F0F0)
    GUICtrlSetBkColor(-1, 0x333333)

    ; We create ONE WebView2 for the entire sidebar
    Local $oWebV2M = _NetWebView2_CreateManager()
    Local $oBridge = _NetWebView2_GetBridge($oWebV2M, "JS_Events_")

    ; Initialize on the left side (0, 0, 140, 410)
    _NetWebView2_Initialize($oWebV2M, $hGui, @ScriptDir & "\UserData", 0, 0, 140, 410, True)

    ; Constructing the HTML with all the buttons
    Local $sHTML = _GenerateSidebarHTML()
    _NetWebView2_NavigateToString($oWebV2M, $sHTML)

    GUISetState(@SW_SHOW)

    While 1
        Switch GUIGetMsg()
            Case $GUI_EVENT_CLOSE
                ExitLoop
        EndSwitch
    WEnd

    _NetWebView2_CleanUp($oWebV2M, $oBridge)
EndFunc   ;==>_Example
;---------------------------------------------------------------------------------------
Func _GenerateSidebarHTML() ; The function that creates the "Menu"
    Local $sCSS = "body { margin: 0; background: #252526; font-family: 'Segoe UI', sans-serif; overflow: hidden; padding: 10px; }" & _
            ".btn { " & _
            "  width: 100%; padding: 12px; margin-bottom: 8px; border: none; border-radius: 6px; " & _
            "  background: #333; color: white; text-align: left; cursor: pointer; font-size: 15px; " & _
            "  transition: 0.2s; display: flex; align-items: center; " & _
            "} " & _
            ".btn:hover { background: #444; transform: translateX(5px); } " & _
            ".btn span { margin-right: 10px; font-size: 18px; }"

    Local $sHTML = "<html><head><style>" & $sCSS & "</style></head><body>"

    Local $aLabels[7] = ["🏆 Trophy", "🎯 Target", "⚠️ Warning", "😎 Cool", "👉 Select", "🌏 World", "🚧 Work"]

    For $i = 0 To 6
        $sHTML &= "<button class='btn' onclick='window.chrome.webview.postMessage(""BTN_CLICKED:" & $i & """)'>" & _
                "<span>" & StringLeft($aLabels[$i], 2) & "</span>" & StringTrimLeft($aLabels[$i], 2) & "</button>"
    Next

    $sHTML &= "</body></html>"
    Return $sHTML
EndFunc   ;==>_GenerateSidebarHTML
;---------------------------------------------------------------------------------------
Volatile Func JS_Events_OnMessageReceived($oWebV2M, $hGui, $sMessage) ; The Bridge that "catches" clicks
    If StringLeft($sMessage, 12) = "BTN_CLICKED:" Then
        Local $sIndex = StringTrimLeft($sMessage, 12)
        ; Here you can call any AutoIt function
        ; ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
        MemoWrite("Index button pressed: " & $sIndex)
    EndIf
EndFunc   ;==>JS_Events_OnMessageReceived
;---------------------------------------------------------------------------------------
Func MemoWrite($sMessage) ; Write a line to the memo control
    GUICtrlSetData($g_idMemo, $sMessage & @CRLF, 1)
EndFunc   ;==>MemoWrite
;---------------------------------------------------------------------------------------

 

Please, every comment is appreciated!
leave your comments and experiences here!
Thank you very much  :)

 

Edited by ioa747

I know that I know nothing

Posted

Commit to github.com as new example
then I take it there and check

Signature beginning:
* Please remember: "AutoIt"..... *  Wondering who uses AutoIt and what it can be used for ? * Forum Rules *
* ADO.au3 UDF * POP3.au3 UDF * XML.au3 UDF * IE on Windows 11 * How to ask ChatGPT for AutoIt Code * for other useful stuff click the following button:

Spoiler

Any of my own code posted anywhere on the forum is available for use by others without any restriction of any kind. 

My contribution (my own projects): * Debenu Quick PDF Library - UDF * Debenu PDF Viewer SDK - UDF * Acrobat Reader - ActiveX Viewer * UDF for PDFCreator v1.x.x * XZip - UDF * AppCompatFlags UDF * CrowdinAPI UDF * _WinMergeCompare2Files() * _JavaExceptionAdd() * _IsBeta() * Writing DPI Awareness App - workaround * _AutoIt_RequiredVersion() * Chilkatsoft.au3 UDF * TeamViewer.au3 UDF * JavaManagement UDF * VIES over SOAP * WinSCP UDF * GHAPI UDF - modest begining - comunication with GitHub REST API * ErrorLog.au3 UDF - A logging Library * Include Dependency Tree (Tool for analyzing script relations) * Show_Macro_Values.au3 *

 

My contribution to others projects or UDF based on  others projects: * _sql.au3 UDF  * POP3.au3 UDF *  RTF Printer - UDF * XML.au3 UDF * ADO.au3 UDF * SMTP Mailer UDF * Dual Monitor resolution detection * * 2GUI on Dual Monitor System * _SciLexer.au3 UDF * SciTE - Lexer for console pane * 

Useful links: * Forum Rules * Forum etiquette *  Forum Information and FAQs * How to post code on the forum * AutoIt Online Documentation * AutoIt Online Beta Documentation * SciTE4AutoIt3 getting started * Convert text blocks to AutoIt code * Games made in Autoit * Programming related sites * Polish AutoIt Tutorial * DllCall Code Generator * 

Wiki: * Expand your knowledge - AutoIt Wiki * Collection of User Defined Functions * How to use HelpFile * Good coding practices in AutoIt * 

OpenOffice/LibreOffice/XLS Related: WriterDemo.au3 * XLS/MDB from scratch with ADOX

IE Related:  * How to use IE.au3  UDF with  AutoIt v3.3.14.x * Why isn't Autoit able to click a Javascript Dialog? * Clicking javascript button with no ID * IE document >> save as MHT file * IETab Switcher (by LarsJ ) * HTML Entities * _IEquerySelectorAll() (by uncommon) * IE in TaskScheduler * IE Embedded Control Versioning (use IE9+ and HTML5 in a GUI) * PDF Related: * How to get reference to PDF object embeded in IE * IE on Windows 11 * 

I encourage you to read: * Global Vars * Best Coding Practices * Please explain code used in Help file for several File functions * OOP-like approach in AutoIt * UDF-Spec Questions *  EXAMPLE: How To Catch ConsoleWrite() output to a file or to CMD *

I also encourage you to check awesome @trancexx code:  * Create COM objects from modules without any demand on user to register anything. * Another COM object registering stuff * OnHungApp handler * Avoid "AutoIt Error" message box in unknown errors  * HTML editor * 

winhttp.au3 related : * https://www.autoitscript.com/forum/topic/206771-winhttpau3-download-problem-youre-speaking-plain-http-to-an-ssl-enabled-server-port/

"Homo sum; humani nil a me alienum puto" - Publius Terentius Afer
"Program are meant to be read by humans and only incidentally for computers and execute" - Donald Knuth, "The Art of Computer Programming"
:naughty:  :ranting:, be  :) and       \\//_.

Anticipating Errors :  "Any program that accepts data from a user must include code to validate that data before sending it to the data store. You cannot rely on the data store, ...., or even your programming language to notify you of problems. You must check every byte entered by your users, making sure that data is the correct type for its field and that required fields are not empty."

Signature last update: 2023-04-24

Posted

Works well

Signature beginning:
* Please remember: "AutoIt"..... *  Wondering who uses AutoIt and what it can be used for ? * Forum Rules *
* ADO.au3 UDF * POP3.au3 UDF * XML.au3 UDF * IE on Windows 11 * How to ask ChatGPT for AutoIt Code * for other useful stuff click the following button:

Spoiler

Any of my own code posted anywhere on the forum is available for use by others without any restriction of any kind. 

My contribution (my own projects): * Debenu Quick PDF Library - UDF * Debenu PDF Viewer SDK - UDF * Acrobat Reader - ActiveX Viewer * UDF for PDFCreator v1.x.x * XZip - UDF * AppCompatFlags UDF * CrowdinAPI UDF * _WinMergeCompare2Files() * _JavaExceptionAdd() * _IsBeta() * Writing DPI Awareness App - workaround * _AutoIt_RequiredVersion() * Chilkatsoft.au3 UDF * TeamViewer.au3 UDF * JavaManagement UDF * VIES over SOAP * WinSCP UDF * GHAPI UDF - modest begining - comunication with GitHub REST API * ErrorLog.au3 UDF - A logging Library * Include Dependency Tree (Tool for analyzing script relations) * Show_Macro_Values.au3 *

 

My contribution to others projects or UDF based on  others projects: * _sql.au3 UDF  * POP3.au3 UDF *  RTF Printer - UDF * XML.au3 UDF * ADO.au3 UDF * SMTP Mailer UDF * Dual Monitor resolution detection * * 2GUI on Dual Monitor System * _SciLexer.au3 UDF * SciTE - Lexer for console pane * 

Useful links: * Forum Rules * Forum etiquette *  Forum Information and FAQs * How to post code on the forum * AutoIt Online Documentation * AutoIt Online Beta Documentation * SciTE4AutoIt3 getting started * Convert text blocks to AutoIt code * Games made in Autoit * Programming related sites * Polish AutoIt Tutorial * DllCall Code Generator * 

Wiki: * Expand your knowledge - AutoIt Wiki * Collection of User Defined Functions * How to use HelpFile * Good coding practices in AutoIt * 

OpenOffice/LibreOffice/XLS Related: WriterDemo.au3 * XLS/MDB from scratch with ADOX

IE Related:  * How to use IE.au3  UDF with  AutoIt v3.3.14.x * Why isn't Autoit able to click a Javascript Dialog? * Clicking javascript button with no ID * IE document >> save as MHT file * IETab Switcher (by LarsJ ) * HTML Entities * _IEquerySelectorAll() (by uncommon) * IE in TaskScheduler * IE Embedded Control Versioning (use IE9+ and HTML5 in a GUI) * PDF Related: * How to get reference to PDF object embeded in IE * IE on Windows 11 * 

I encourage you to read: * Global Vars * Best Coding Practices * Please explain code used in Help file for several File functions * OOP-like approach in AutoIt * UDF-Spec Questions *  EXAMPLE: How To Catch ConsoleWrite() output to a file or to CMD *

I also encourage you to check awesome @trancexx code:  * Create COM objects from modules without any demand on user to register anything. * Another COM object registering stuff * OnHungApp handler * Avoid "AutoIt Error" message box in unknown errors  * HTML editor * 

winhttp.au3 related : * https://www.autoitscript.com/forum/topic/206771-winhttpau3-download-problem-youre-speaking-plain-http-to-an-ssl-enabled-server-port/

"Homo sum; humani nil a me alienum puto" - Publius Terentius Afer
"Program are meant to be read by humans and only incidentally for computers and execute" - Donald Knuth, "The Art of Computer Programming"
:naughty:  :ranting:, be  :) and       \\//_.

Anticipating Errors :  "Any program that accepts data from a user must include code to validate that data before sending it to the data store. You cannot rely on the data store, ...., or even your programming language to notify you of problems. You must check every byte entered by your users, making sure that data is the correct type for its field and that required fields are not empty."

Signature last update: 2023-04-24

Posted

@ioa747 I like the idea of web based UI. Is there any other prerequisites for this to work. I ask because I have a bunch of stuffs installed on my PC and it was fairly simple to register the components and run the sample code provided and everything works properly. To deploy an application are there any other prerequisites?

Posted (edited)

 

📦 Deployment & Installation

      Extract the NetWebView2Lib folder to a permanent location.

      Clean & Prepare (Essential Step):
      If you have a previous version installed, it is highly recommended to run the included \bin\RegCleaner.au3 before registering the new version.
      This ensures that any stale registry entries from previous builds are purged, preventing "Object action failed" errors and GUID conflicts.

      Registration:
      
Run \bin\Register_web2.au3 to register the library.
      This script verifies the WebView2 Runtime presence and registers NetWebView2Lib.dll for COM Interop on both 32-bit and 64-bit architectures.

      Uninstallation:
      To remove the library from your system, simply run \bin\Unregister.au3.

      Run Examples:
      Execute any script in the \Example\* folder to see the bridge in action.

 

🛠 Prerequisites

    .NET Framework 4.8 or higher.
    Microsoft Edge WebView2 Runtime version 128.0.2739.15 or higher.

 

https://github.com/ioa747/NetWebView2Lib

Edited by ioa747

I know that I know nothing

Posted

New Version (v2.2.1-alpha1) has arrived
I updated the first post  :)   

 

🛠️ Migration Note (Important)

Due to changes in the COM Dispatch IDs (DispIds) for better organization, it is  highly recommended  to run the included  RegCleaner.au3  before registering the new version. This ensures that any stale registry entries from previous builds are purged, preventing "Object action failed" errors.

 

512.webp  Caution

Breaking Change: If you have custom scripts using OnWebResourceResponseReceived or OnDownloadStateChanged,
please update their signatures to use the new $oArgs object as demonstrated in the updated examples.

 

I know that I know nothing

Posted (edited)

New Version (v2.2.2-alpha) has arrived
I updated the first post  :)   

 

🛠️ What's New

Provide a configurable throttling mechanism for messages sent from JavaScript to AutoIt via the WebView2 bridge to prevent message loss
when throttling is too restrictive for certain use cases, while keeping safety defaults.

Implement the ThrottlingIntervalMs property to the object
Gets or sets the throttling interval in milliseconds for messages sent from JavaScript to AutoIt.
Set to 0 to disable throttling entirely. Default is 20ms.
object.ThrottlingIntervalMs = 20

and as a new parameter to the signature of _NetWebView2_CreateManager

_NetWebView2_CreateManager($sUserAgent = "", $s_fnEventPrefix = "", $s_AddBrowserArgs = "", $bVerbose = False, $iThrottlingIntervalMs = 20)

$iThrottlingIntervalMs - [optional] an integer value. Sets the JS-to-AutoIt message throttling interval in ms. (Default = 20.)

examples/024-ConfigurableThrottling.au3

Edited by ioa747

I know that I know nothing

  • 3 months later...
Posted

sorry!
can it had the function about trans languages??
it is need for not english languages users to brower web ..
^____^""

 

-Everything are starting by the dreams.-Everybody is working with computer.-Everydays will auto because we need it. Come on..Let's doing...AUTOIT....^^"..just a little idea..a little A.D.

Posted (edited)

Here is a full, ready-to-run script demonstrating how to integrate a basic navigation bar using NetWebView2Lib.

For a detailed step-by-step breakdown on managing Chrome/Edge extensions with this library, check out the guide here: 🔗 How-To: Using Extensions in NetWebView2

#AutoIt3Wrapper_UseX64=y
#AutoIt3Wrapper_Run_AU3Check=Y
#AutoIt3Wrapper_AU3Check_Stop_OnWarning=y
#AutoIt3Wrapper_AU3Check_Parameters=-d -w 1 -w 2 -w 3 -w 4 -w 5 -w 6 -w 7

#include <GUIConstantsEx.au3>
#include <WindowsConstants.au3>
#include <EditConstants.au3>
#include <Misc.au3>
#include <GuiMenu.au3>
#include <WinAPIMisc.au3>

#include "..\NetWebView2Lib.au3"
;~ #include "_WV2_ExtensionPicker.au3"

; Check if the version supports Maps
If _VersionCompare(@AutoItVersion, "3.3.16.0") < 0 Then
    MsgBox($MB_ICONSTOP, "Compatibility Error", _
            "This version of the script uses Maps and requires AutoIt 3.3.16.0 or higher." & @CRLF & _
            "Your version: " & @AutoItVersion)
    Exit
EndIf


; Global objects
Global $_mBAR
Global $sProfileDirectory = @ScriptDir & "\NetWebView2Lib-UserDataFolder"

_Example()

Func _Example()
    ConsoleWrite("! MicrosoftEdgeWebview2 : version check: " & _NetWebView2_IsAlreadyInstalled() & ' ERR=' & @error & ' EXT=' & @extended & @CRLF)

    Local $hDLL = DllOpen("user32.dll")
    Local $oMyError = ObjEvent("AutoIt.Error", __NetWebView2_COMErrFunc)
    #forceref $oMyError

    ; Create the GUI
    Local $hGUI = GUICreate("WebView2", 1000, 800, -1, -1, BitOR($WS_OVERLAPPEDWINDOW, $WS_CLIPCHILDREN))
    GUISetBkColor(0x2B2B2B, $hGUI)

    ; Initialize WebView2 Manager and register events
    Local $oWebV2M = _NetWebView2_CreateManager("", "Event_", "--enable-features=Translate,msEdgeTranslate --enable-builtin-translation --lang=el") ; 🚧 --lang=el ??
    If @error Then Return SetError(@error, @extended, $oWebV2M)

    ; create JavaScript Bridge object
    Local $oJSBridge = _NetWebView2_GetBridge($oWebV2M, "")
    If @error Then Return SetError(@error, @extended, $oWebV2M)

    ; initialize browser - put it on the GUI
    _NetWebView2_Initialize($oWebV2M, $hGUI, $sProfileDirectory, 0, 25, 1000, 800 - 25, True, True, 1.2, "0x2B2B2B")

    ; Make a Basic ToolBar for Browsing navigation
    $_mBAR = _Web_MakeBar($hGUI, $oWebV2M, 1)

    ; show the GUI after browser was fully initialized
    GUISetState(@SW_SHOW)

    ; navigate to the page
    _NetWebView2_Navigate($oWebV2M, "https://en.wikipedia.org/wiki/List_of_countries_and_dependencies_by_population")
    ConsoleWrite("navigate to the page" & @CRLF)

    ; Main Loop
    Local $iMsg
    While 1
        $iMsg = GUIGetMsg()
        Switch $iMsg
            Case $GUI_EVENT_CLOSE
                ExitLoop

            Case $_mBAR.Navigation
                _Web_NavButton()

            Case $_mBAR.Address
                If _IsPressed("0D", $hDLL) Then ; ENTER key
                    _Web_NavButton("Navigate")
                    _Web_NavButton()
                Else
                    AdlibRegister(_Web_SetNavigateToReload, 700)
                EndIf

            Case $_mBAR.GoBack
                $oWebV2M.GoBack()

            Case $_mBAR.GoForward
                $oWebV2M.GoForward()

            Case $_mBAR.Application_Menu
                _ShowApplicationMenu($oWebV2M, $hGUI)

            Case $_mBAR.Translate
                ; Option 1: URL Redirection via Google Translate Proxy (Recommended)
;~              _TranslateGoogle($oWebV2M, GUICtrlRead($_mBAR.Address), "el") ; 🚧 "zh-CN"

                ; Option 2: Dynamic JavaScript Injection
                _InjectGoogleTranslate($oWebV2M, "el") ; 🚧 "zh-CN"

        EndSwitch

        ; AddressBar FullSelection Management
        If $_mBAR.bURLFullSelected Then
            $_mBAR.bURLFullSelected = False
            GUICtrlSendMsg($_mBAR.Address, $EM_SETSEL, 0, -1)
        EndIf

    WEnd

    _NetWebView2_CleanUp($oWebV2M, $oJSBridge)
    GUIDelete($hGUI)
    DllClose($hDLL)
EndFunc   ;==>_Example

;---------------------------------------------------------------------------------------
Func _ShowApplicationMenu($oWebV2M, $hGUI)
    Local $hMenu = _GUICtrlMenu_CreatePopup()
    _GUICtrlMenu_AddMenuItem($hMenu, "Google", 1001)
    _GUICtrlMenu_AddMenuItem($hMenu, "AutoIt", 1002)
    _GUICtrlMenu_AddMenuItem($hMenu, "wikipedia", 1003)
    _GUICtrlMenu_AddMenuItem($hMenu, "demoqa", 1004)
    _GUICtrlMenu_AddMenuItem($hMenu, "microsoft", 1005)
    _GUICtrlMenu_AddMenuItem($hMenu, "") ; separator
    _GUICtrlMenu_AddMenuItem($hMenu, "Clear browser history", 1021)

    Local $tPos = _WinAPI_GetMousePos()
    Local $iCmd = _GUICtrlMenu_TrackPopupMenu($hMenu, $hGUI, DllStructGetData($tPos, "X"), DllStructGetData($tPos, "Y"), 1, 1, 2)

    Switch $iCmd
        Case 1001
            _Web_GoTo($oWebV2M, "https://www.google.com")
        Case 1002
            _Web_GoTo($oWebV2M, "https://www.autoitscript.com/forum")
        Case 1003
            _Web_GoTo($oWebV2M, "https://en.wikipedia.org/wiki/List_of_countries_and_dependencies_by_population")
        Case 1004
            _Web_GoTo($oWebV2M, "https://demoqa.com/text-box")
        Case 1005
            _Web_GoTo($oWebV2M, "https://learn.microsoft.com/en-us/dotnet/api/microsoft.web.webview2.core.corewebview2profile.addbrowserextensionasync?view=webview2-dotnet-1.0.3595.46")
        Case 1021
            If MsgBox(36, "Confirm", "Clear all browser history/cookies?") = 6 Then $oWebV2M.ClearBrowserData()
    EndSwitch
    _GUICtrlMenu_DestroyMenu($hMenu)
    $oWebV2M.WebViewSetFocus() ; We give focus to the browser
EndFunc   ;==>_ShowApplicationMenu

;---------------------------------------------------------------------------------------
Func Event_OnNavigationCompleted($oWebV2M, $hGUI, $bSuccess, $iError) ; EVENT HANDLERS (CALLBACKS)
    #forceref $hGUI, $bSuccess, $iError
    ConsoleWrite(">>>$bSuccess=" & $bSuccess & @CRLF)
    $oWebV2M.ExecuteScript("finalizeProgress();")

    GUICtrlSetData($_mBAR.Address, $oWebV2M.GetSource())
    _Web_NavButton("Reload")

    ; Using the new Getters for dynamic UI
    GUICtrlSetState($_mBAR.GoBack, ($oWebV2M.GetCanGoBack() ? $GUI_ENABLE : $GUI_DISABLE))
    GUICtrlSetState($_mBAR.GoForward, ($oWebV2M.GetCanGoForward() ? $GUI_ENABLE : $GUI_DISABLE))
    $oWebV2M.WebViewSetFocus() ; We give focus to the browser
EndFunc   ;==>Event_OnNavigationCompleted

;---------------------------------------------------------------------------------------
Func _Web_MakeBar($hGUI, $oWebV2M, $bAddress = 1) ; Make a Basic ToolBar for Browsing navigation
    ; Defining the main buttons with the Fluent Icons
    Local $Btn[][] = _
            [ _
            [59136, "Application_Menu"], _
            [59253, "Translate"], _
            [59179, "GoBack"], _
            [59178, "GoForward"], _
            [59180, "Navigation"] _
            ]

    Local $iX = 0, $iY = 0, $iH = 25, $iW = 25, $iCnt = UBound($Btn)
    Local $mBAR[] ; Map object to return IDs

    ; Creating the Buttons
    For $i = 0 To $iCnt - 1
        $mBAR[$Btn[$i][1]] = GUICtrlCreateButton(ChrW($Btn[$i][0]), $iX, $iY, $iW, $iH)
        GUICtrlSetFont(-1, 12, 400, 0, "Segoe Fluent Icons")
        GUICtrlSetTip(-1, StringReplace($Btn[$i][1], "_", " "))
        GUICtrlSetResizing(-1, $GUI_DOCKALL)
        $iX += $iW
    Next

    ; Creating the Address Bar
    Local $aCsz = WinGetClientSize($hGUI)
    Local $iInputW = $aCsz[0] - $iX - 15
    $mBAR.Address = GUICtrlCreateInput("", $iX, $iY, $iInputW, $iH)
    GUICtrlSetFont(-1, 11, 400, 0, "Segoe UI")
    GUICtrlSetResizing(-1, $GUI_DOCKLEFT + $GUI_DOCKRIGHT + $GUI_DOCKMENUBAR)
    If Not $bAddress Then GUICtrlSetState(-1, $GUI_HIDE)

    $mBAR.bURLFullSelected = False

    $mBAR.WebV2M = $oWebV2M
    Return $mBAR
EndFunc   ;==>_Web_MakeBar

;---------------------------------------------------------------------------------------
Func _Web_NavButton($sSetState = Default) ; Set or executes the action of Navigation button (Reload/Stop/Navigate)
    Local Static $sState = "Reload"

    ; 59180 = Reload ; 59153 = Cancel ; 59217 = ReturnKey
    Local $oWebV2M = $_mBAR.WebV2M
    If $sSetState <> Default Then
        Switch $sSetState
            Case "Reload"
                GUICtrlSetData($_mBAR.Navigation, ChrW(59180))
                GUICtrlSetTip($_mBAR.Navigation, "Reload")
            Case "Stop"
                GUICtrlSetData($_mBAR.Navigation, ChrW(59153))
                GUICtrlSetTip($_mBAR.Navigation, "Stop")
            Case "Navigate"
                If $sState = $sSetState Then Return
                AdlibUnRegister(_Web_SetNavigateToReload) ; UnRegister it (if exist)
                GUICtrlSetData($_mBAR.Navigation, ChrW(59217))
                GUICtrlSetTip($_mBAR.Navigation, "Navigate")
        EndSwitch
        $sState = $sSetState
        Return
    EndIf

    Switch $sState
        Case "Reload"
            $oWebV2M.Reload()
        Case "Stop"
            $oWebV2M.Stop()
        Case "Navigate"
            Sleep(100)
            _Web_GoTo($oWebV2M, GUICtrlRead($_mBAR.Address))
    EndSwitch
EndFunc   ;==>_Web_NavButton

;---------------------------------------------------------------------------------------
Func _Web_SetNavigateToReload() ; AdlibRegister("_Web_SetNavigateToReload", 700), and forget it
    _Web_NavButton("Reload")
    AdlibUnRegister(_Web_SetNavigateToReload) ; unregister itself.
EndFunc   ;==>_Web_SetNavigateToReload

;---------------------------------------------------------------------------------------
Func _Web_GoTo($oWebV2M, $sURL) ; Navigates to a URL or performs a Google search if the input is not a URL.
    $sURL = StringStripWS($sURL, 3)
    If $sURL = "" Then Return False

    ; Check if it already has a protocol (http://, https://, file://, etc.)
    Local $bHasProtocol = StringRegExp($sURL, '(?i)^[a-z]+://', 0)

    ; Check if it looks like a domain (e.g., test.com, autoitscript.com)
    Local $bIsURL = StringRegExp($sURL, '(?i)^([a-z0-9\-]+\.)+[a-z]{2,}', 0)
    Local $sFinalURL = ""

    If $bHasProtocol Then
        $sFinalURL = $sURL
    ElseIf $bIsURL Then
        ; Prepend https for domains without protocol
        $sFinalURL = "https://" & $sURL
    Else
        ; It's a search query. Use the new EncodeURI for perfect character handling
        $sFinalURL = "https://www.google.com/search?q=" & $oWebV2M.EncodeURI($sURL)
    EndIf

    ; Execution
    ConsoleWrite("-> Web_GoTo: " & $sFinalURL & @CRLF)
    _NetWebView2_Navigate($oWebV2M, $sFinalURL)
    Return True
EndFunc   ;==>_Web_GoTo

;---------------------------------------------------------------------------------------
Func WM_COMMAND($hWnd, $iMsg, $wParam, $lParam) ; Register the WM_COMMAND (CALLBACKS) to handle AddressBar FullSelection
    #forceref $hWnd, $iMsg
    Local Static $hidURL = GUICtrlGetHandle($_mBAR.Address)
    Local $iCode = BitShift($wParam, 16)
    If $lParam = $hidURL Then
        Switch $iCode
            Case $EN_SETFOCUS
                $_mBAR.bURLFullSelected = True
            Case $EN_CHANGE
                _Web_NavButton("Navigate")
        EndSwitch
    EndIf
    Return $GUI_RUNDEFMSG
EndFunc   ;==>WM_COMMAND
;---------------------------------------------------------------------------------------

; Option 1: URL Redirection via Google Translate Proxy (Recommended) 🚧
Func _TranslateGoogle($oWebV2M, $sOriginalURL, $sTargetLang = "en")
    Local $sTranslatedURL = "https://translate.google.com/translate?sl=auto&tl=" & $sTargetLang & "&u=" & $sOriginalURL
    _NetWebView2_Navigate($oWebV2M, $sTranslatedURL)
EndFunc   ;==>_TranslateGoogle

; Option 2: Dynamic JavaScript Injection 🚧
Func _InjectGoogleTranslate($oWV, $sTargetLang = "en")
    Local $sJS = ""
    $sJS &= "(function() {"
    $sJS &= "    if (document.getElementById('google_translate_element')) return;"

    ; We define the first callback function in the window.
    $sJS &= "    window.googleTranslateElementInit = function() {"
    $sJS &= "        new google.translate.TranslateElement({"
    $sJS &= "            pageLanguage: 'auto',"
    $sJS &= "            layout: google.translate.TranslateElement.InlineLayout.VERTICAL"
    $sJS &= "        }, 'google_translate_element');"

    ; Auto-trigger language switch after initialization
    $sJS &= "        setTimeout(function() {"
    $sJS &= "            var select = document.querySelector('.goog-te-combo');"
    $sJS &= "            if (select) {"
    $sJS &= "                select.value = '" & $sTargetLang & "';"
    $sJS &= "                select.dispatchEvent(new Event('change'));"
    $sJS &= "            }"
    $sJS &= "        }, 500);"
    $sJS &= "    };"

    ; We create the container div
    $sJS &= "    var gDiv = document.createElement('div');"
    $sJS &= "    gDiv.id = 'google_translate_element';"
    $sJS &= "    document.body.insertBefore(gDiv, document.body.firstChild);"

    ; We are loading the final external script.
    $sJS &= "    var gScript = document.createElement('script');"
    $sJS &= "    gScript.type = 'text/javascript';"
    $sJS &= "    gScript.src = 'https://translate.google.com/translate_a/element.js?cb=googleTranslateElementInit';"
    $sJS &= "    document.body.appendChild(gScript);"
    $sJS &= "})();"

    _NetWebView2_ExecuteScript($oWV, $sJS)
EndFunc   ;==>_InjectGoogleTranslate

 

Pay attention to the  '🚧'

Edited by ioa747
update

I know that I know nothing

Posted

Thanks you!Iwill to try it.

-Everything are starting by the dreams.-Everybody is working with computer.-Everydays will auto because we need it. Come on..Let's doing...AUTOIT....^^"..just a little idea..a little A.D.

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
×
×
  • Create New...