Jump to content

WebView2AutoIt - AutoIt WebView2 Component (COM Interop)


Recommended Posts

Posted
27 minutes ago, ioa747 said:

This project enables you to render modern HTML5, CSS3, and JavaScript directly inside your AutoIt applications.

---------------------------
Error
---------------------------
Could not create WebView2 Manager. Please register the DLL.
---------------------------
OK
---------------------------

😭

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

Posted (edited)

:lol:  There are two ways
either you will load "NetWebView2\WebView2AutoIt_v0.1\NetWebView2Lib\NetWebView2Lib.sln"
into Visual Studio and build
or you will run "\WebView2AutoIt_v0.1\NetWebView2Lib\WebView2AutoIt\register_web2.au3"

ah! there is also a "WebView2AutoIt_v0.1\README.md"

Edited by ioa747

I know that I know nothing

Posted

If MsgBox(36, "Confirm", "Exit Application?", 0, $hGUI) = 6 Then Exit  is better because it will disable the GUI while MsgBox() is active.

Is there a way to do all these without registering a DLL ?
- I hope someone with more knowledge can shed some light on the thread.
Ok, but, it would be nicer, even if not better than this way.

Thanks for the code :) 
 

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

Posted

Nice thanks.

Will look into it, hope in next 2 month. My january schedule is full as always from 20years.

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 Codefor 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 APIErrorLog.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 TaskSchedulerIE 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 stuffOnHungApp handlerAvoid "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

Interesting, thank you @ioa747 👌 . This could bring a large opportunity to AutoIt in cases of working witz the web (html, js etc.).

I will also have a look after the christmas days. I would also be interested in the .Net (C#) bridge that you build. Maybe you provide the code also in the zip file? Or separately?

In any case, thanks and enjoy the upcoming days with your beloved ones.

Best regards

Sven

==> AutoIt related: 🔗 GitHub, 🔗 Discord Server, 🔗 Cheat Sheet🔗 autoit-webdriver-boilerplate

Spoiler

🌍 Au3Forums

🎲 AutoIt (en) Cheat Sheet

📊 AutoIt limits/defaults

💎 Code Katas: [...] (comming soon)

🎭 Collection of GitHub users with AutoIt projects

🐞 False-Positives

🔮 Me on GitHub

💬 Opinion about new forum sub category

📑 UDF wiki list

✂ VSCode-AutoItSnippets

📑 WebDriver FAQs

👨‍🏫 WebDriver Tutorial (coming soon)

Posted


Τhank you SOLVE-SMART, every contribution is welcome
All files are in the zip file, in the first post
I am definitely still in the process of searching and enriching (according to my capabilities)
since new doors are opening

I know that I know nothing

Posted (edited)

Thanks for sharing


Is there a way to integrate extension support?

coreWebView2.Profile.AddBrowserExtensionAsync("folder containing manifest.json");

 

https://learn.microsoft.com/en-us/dotnet/api/microsoft.web.webview2.core.corewebview2profile.addbrowserextensionasync?view=webview2-dotnet-1.0.3595.46

 

 

edit

i add this to WebViewManager.cs and compiled, but this is not working. 

i get only a white screen.

 

var options = new CoreWebView2EnvironmentOptions(userDataFolder);
options.AreBrowserExtensionsEnabled = true;
var path = @"D:\WebView2AutoIt_v0.1\uBOLite_2025.1224.1544.edge\";
await _webView.CoreWebView2.Profile.AddBrowserExtensionAsync(path);

 

WebViewManager.cs

Edited by bladem2003
Posted (edited)

Update to Version 1.3.0  - (2025-12-25)

the main change is that now
.Initialize(hWnd, userDataFolder, x, y, width, height)
in the second parameter takes the userDataFolder, and not the url, as it was until now

Specifying the userDataFolder gives us the advantage of having multiple separate/isolated entities
e.g. 2 facebook accounts simultaneously side by side

Persistent Sessions: Cookies, Local Storage, and browser cache are now saved in a dedicated directory.
This means users stay logged into websites even after the application restarts.

Environment Isolation: By defining a specific path, you ensure that your application's data is isolated from other WebView2 instances or the system's default browser profile.

Improved Stability: It prevents permission conflicts. If the parameter is left as an empty string "", the engine defaults to the executable's directory.

However, providing a path like @AppDataDir ensures the application runs correctly even when installed in restricted folders like Program Files.


Νow supports loading unpacked Chromium extensions.
This allows you to enhance the browser's functionality with custom tools or third-party extensions.

Method: .AddExtension($sExtPath)
Requirement: The extension must be in an "unpacked" format (a folder containing the manifest.json file).
(analytical guide to WebView2AutoIt\Doc\How-To Using Extensions in NetWebView2.md)
Example   WebView2AutoIt\Examples\6-Multi-WebView2-Extension.au3

 

Other Improvements:

New Method: .IsReady()  A boolean check to confirm the browser engine has finished initializing before sending commands like .Navigate().

Enhanced Cleanup: The .Cleanup() method has been optimized to ensure all Chromium processes are terminated
and file locks on the userDataFolder are released immediately.


Template

#AutoIt3Wrapper_UseX64=y
#include <GUIConstantsEx.au3>
#include <WindowsConstants.au3>

; =======================================================================================
; PROJECT: WebView2 .NET Manager - Starter Template
; DESCRIPTION: A clean skeleton for integrating Chromium (WebView2) into AutoIt.
; VERSION: 1.3.0
; =======================================================================================

OnAutoItExitRegister ("_ExitApp")

; Global objects for COM Interop
Global $oWeb, $oBridge
Global $oEvtManager, $oEvtBridge
Global $hGUI, $sURL = "https://www.google.com"
Global $oMyError = ObjEvent("AutoIt.Error", "_ErrFunc") ; Will be called if COM error occurs

; 1. Create the Main GUI
$hGUI = GUICreate("WebView2 v1.3.0 - Starter Template", 1024, 768, -1, -1, BitOR($WS_OVERLAPPEDWINDOW, $WS_CLIPCHILDREN))
GUISetBkColor(0x1E1E1E, $hGUI)

; 2. Initialize the COM Objects
_InitWebView()

; 3. Main Application Loop
GUISetState(@SW_SHOW)

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

; =======================================================================================
; CORE FUNCTIONS
; =======================================================================================

Func _InitWebView()
    ; A. Create the Manager Instance
    $oWeb = ObjCreate("NetWebView2.Manager")
    If Not IsObj($oWeb) Then Return MsgBox(16, "Error", "WebView2 DLL not registered!")

    ; B. Register Manager Events (Navigation, Status, Core Messages)
    $oEvtManager = ObjEvent($oWeb, "WebView_", "IWebViewEvents")

    ; C. Setup the JavaScript Bridge (Communication from JS to AutoIt)
    $oBridge = $oWeb.GetBridge()
    $oEvtBridge = ObjEvent($oBridge, "Bridge_", "IBridgeEvents")

    ; D. Initialize the browser engine
    
    ; Browser Data Directory (Cache, Cookies, Session).
    ; Ensures that settings and logins persist after closing the application.
    ; - If left blank "", the folder will be automatically created next to the executable.
    ; - ⚠️ WARNING: If you are running the script from Scite (C:\Program Files (x86)\AutoIt3),
    ; make sure you have write permissions to the folder, otherwise set a path
    ; to another location (e.g. @AppDataDir & "\MyApp").
    Local $sProfilePath = @ScriptDir & "\UserDataFolder"
    
    ; ⚠️ IMPORTANT: Enclose ($hGUI) in parentheses to force "Pass-by-Value" (COM requirement).
    ; Parameters: (hWnd, profilePath, x, y, width, height)
    $oWeb.Initialize(($hGUI), $sProfilePath, 0, 0, 1024, 768)

    ; E. Wait for the engine to be ready before navigating
    Do
        Sleep(50)
    Until $oWeb.IsReady

    ; F. Navigate to the starting URL
    $oWeb.Navigate($sURL)

    ConsoleWrite("> WebView2 is Ready and Navigating..." & @CRLF)
EndFunc

Func _ExitApp()
    ; ⚠️ IMPORTANT: Cleanup must be called to release file locks on the Profile Folder
    ; and to terminate msedgewebview2.exe processes.
    If IsObj($oWeb) Then $oWeb.Cleanup()

    $oWeb = 0
    $oBridge = 0
    Exit
EndFunc

; =======================================================================================
; EVENT HANDLERS (CALLBACKS)
; =======================================================================================

; Listen for Manager Events (System-level messages)
; Common messages: INIT_READY, NAV_STARTING, NAV_COMPLETED, URL_CHANGED, TITLE_CHANGED
Func WebView_OnMessageReceived($sMsg)
    ConsoleWrite("+> [WebView Manager]: " & $sMsg & @CRLF)
EndFunc

; Listen for JavaScript Bridge Events (Custom messages from the webpage)
; Triggered by: window.chrome.webview.postMessage("your_data_here");
Func Bridge_OnMessageReceived($sMsg)
    ConsoleWrite(">> [JS Bridge]: " & $sMsg & @CRLF)

    ; Example: Simple logic based on JS message
    If $sMsg == "close_window" Then _ExitApp()
EndFunc

; =======================================================================================
; User's COM error function. Will be called if COM error occurs
Func _ErrFunc($oError)
    ; Do anything here.
    ConsoleWrite(@ScriptName & " (" & $oError.scriptline & ") : ==> COM Error intercepted !" & @CRLF & _
            @TAB & "err.number is: " & @TAB & @TAB & "0x" & Hex($oError.number) & @CRLF & _
            @TAB & "err.windescription:" & @TAB & $oError.windescription & @CRLF & _
            @TAB & "err.description is: " & @TAB & $oError.description & @CRLF & _
            @TAB & "err.source is: " & @TAB & @TAB & $oError.source & @CRLF & _
            @TAB & "err.helpfile is: " & @TAB & $oError.helpfile & @CRLF & _
            @TAB & "err.helpcontext is: " & @TAB & $oError.helpcontext & @CRLF & _
            @TAB & "err.lastdllerror is: " & @TAB & $oError.lastdllerror & @CRLF & _
            @TAB & "err.scriptline is: " & @TAB & $oError.scriptline & @CRLF & _
            @TAB & "err.retcode is: " & @TAB & "0x" & Hex($oError.retcode) & @CRLF & @CRLF)
EndFunc   ;==>_ErrFunc

 

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

@ioa747 could you be so nice and share yours CS code over github ?

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 Codefor 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 APIErrorLog.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 TaskSchedulerIE 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 stuffOnHungApp handlerAvoid "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)

I will make an attempt, as I have made an account, but I do not use it and I have no experience. :D
For information, in the zip file the folder WebView2AutoIt\NetWebView2Lib is the solution folder from visual studio

Edited by ioa747

I know that I know nothing

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...