Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
105 changes: 101 additions & 4 deletions NetWebView2Lib.au3
Original file line number Diff line number Diff line change
Expand Up @@ -67,9 +67,7 @@ Global Enum _ ; $NETWEBVIEW2_MESSAGE__* are set by __NetWebView2_WebViewEvents__
; #FUNCTION# ====================================================================================================================
; Name ..........: _NetWebView2_Initialize
; Description ...:
; Syntax ........: _NetWebView2_Initialize(ByRef $oWebV2M, $hGUI, $sProfileDirectory[, $i_Left = 0[, $i_Top = 0[, $i_Width = 0[,
; $i_Height = 0[, $b_LoadWait = True[, $b_SetAutoResize = True[, $b_AreDevToolsEnabled = True[,
; $i_ZoomFactor = 1.0[, $s_BackColor = "0x2B2B2B"]]]]]]]]])
; Syntax ........: _NetWebView2_Initialize(ByRef $oWebV2M, $hGUI, $sProfileDirectory[, $i_Left = 0[, $i_Top = 0[, $i_Width = 0[, $i_Height = 0[, $b_LoadWait = True[, $b_SetAutoResize = True[, $b_AreDevToolsEnabled = True[, $i_ZoomFactor = 1.0[, $s_BackColor = "0x2B2B2B"[, $bInitializeConsoleBridge = False]]]]]]]]]])
; Parameters ....: $oWebV2M - [in/out] an object.
; $hGUI - a handle value.
; $sProfileDirectory - a string value.
Expand All @@ -82,6 +80,7 @@ Global Enum _ ; $NETWEBVIEW2_MESSAGE__* are set by __NetWebView2_WebViewEvents__
; $b_AreDevToolsEnabled- [optional] a boolean value. Default is True.
; $i_ZoomFactor - [optional] an integer value. Default is 1.0.
; $s_BackColor - [optional] a string value. Default is "0x2B2B2B".
; $bInitializeConsoleBridge- [optional] a boolean value. Default is False.
; Return values .: None
; Author ........: mLipok, ioa747
; Modified ......:
Expand All @@ -90,7 +89,7 @@ Global Enum _ ; $NETWEBVIEW2_MESSAGE__* are set by __NetWebView2_WebViewEvents__
; Link ..........:
; Example .......: No
; ===============================================================================================================================
Func _NetWebView2_Initialize(ByRef $oWebV2M, $hGUI, $sProfileDirectory, $i_Left = 0, $i_Top = 0, $i_Width = 0, $i_Height = 0, $b_LoadWait = True, $b_SetAutoResize = True, $b_AreDevToolsEnabled = True, $i_ZoomFactor = 1.0, $s_BackColor = "0x2B2B2B")
Func _NetWebView2_Initialize(ByRef $oWebV2M, $hGUI, $sProfileDirectory, $i_Left = 0, $i_Top = 0, $i_Width = 0, $i_Height = 0, $b_LoadWait = True, $b_SetAutoResize = True, $b_AreDevToolsEnabled = True, $i_ZoomFactor = 1.0, $s_BackColor = "0x2B2B2B", $bInitializeConsoleBridge = False)
Local Const $s_Prefix = "[_NetWebView2_Initialize]:" & " GUI:" & $hGUI & " ProfileDirectory:" & $sProfileDirectory & " LEFT:" & $i_Left & " TOP:" & $i_Top & " WIDTH" & $i_Width & " HEIGHT:" & $i_Height & " LOADWAIT:" & $b_LoadWait & " SETAUTORESIZE:" & $b_SetAutoResize & " SetAutoResize:" & $b_AreDevToolsEnabled & " ZoomFactor:" & $i_ZoomFactor & " BackColor:" & $s_BackColor

; โš ๏ธ Important: Enclose ($hGUI) in parentheses to force "Pass-by-Value".
Expand All @@ -107,6 +106,11 @@ Func _NetWebView2_Initialize(ByRef $oWebV2M, $hGUI, $sProfileDirectory, $i_Left
$oWebV2M.AreDevToolsEnabled = $b_AreDevToolsEnabled ; Allow F12
$oWebV2M.ZoomFactor = $i_ZoomFactor
$oWebV2M.BackColor = $s_BackColor

If $bInitializeConsoleBridge Then
$oWebV2M.AddInitializationScript(__Get_Core_Bridge_JS())
EndIf

If @error Then __NetWebView2_Log(@ScriptLineNumber, $s_Prefix & " Manager Creation ERROR", 1)
Return SetError(@error, $oWebV2M.GetBrowserProcessId(), '')
EndFunc ;==>_NetWebView2_Initialize
Expand Down Expand Up @@ -167,6 +171,7 @@ Func _NetWebView2_GetBridge(ByRef $oWebV2M, $s_fnEventPrefix = "")

If $s_fnEventPrefix Then $_g_sNetWebView2_User_JSEvents = $s_fnEventPrefix
ObjEvent($oWebJS, "__NetWebView2_JSEvents__", "IBridgeEvents")

Return SetError(@error, @extended, $oWebJS)
EndFunc ;==>_NetWebView2_GetBridge

Expand Down Expand Up @@ -616,6 +621,96 @@ Func __NetWebView2_ObjName_FlagsValue(ByRef $oObj)

ConsoleWrite($sInfo & @CRLF)
EndFunc ;==>__NetWebView2_ObjName_FlagsValue

; #INTERNAL_USE_ONLY# ===========================================================================================================
; Name ..........: __Get_Core_Bridge_JS
; Description ...: Get JavaScript for Bridge
; Syntax ........: __Get_Core_Bridge_JS()
; Parameters ....: None
; Return values .: JavaScript for Bridge
; Author ........: ioa747
; Modified ......: mLipok
; Remarks .......:
; Related .......:
; Link ..........:
; Example .......: No
; ===============================================================================================================================
Func __Get_Core_Bridge_JS()
Local $sJS = _
"/**" & @CRLF & _
" * NetWebView2Lib Core Bridge" & @CRLF & _
" * Handles Console Hijacking and Global Error Reporting" & @CRLF & _
" */" & @CRLF & _
"" & @CRLF & _
"(function() {" & @CRLF & _
" // 1. Configuration & State" & @CRLF & _
" window.NET_BRIDGE_ENABLED = true;" & @CRLF & _
"" & @CRLF & _
" /**" & @CRLF & _
" * Centralized message dispatcher to AutoIt" & @CRLF & _
" */" & @CRLF & _
" const dispatchToAutoIt = (data) => {" & @CRLF & _
" try {" & @CRLF & _
" if (window.chrome && window.chrome.webview) {" & @CRLF & _
" window.chrome.webview.postMessage(JSON.stringify(data));" & @CRLF & _
" }" & @CRLF & _
" } catch (e) {" & @CRLF & _
" // Silent fail if bridge is not fully ready" & @CRLF & _
" }" & @CRLF & _
" };" & @CRLF & _
"" & @CRLF & _
" /**" & @CRLF & _
" * Console Hijacking Logic" & @CRLF & _
" */" & @CRLF & _
" const originalConsole = {" & @CRLF & _
" log: console.log," & @CRLF & _
" error: console.error," & @CRLF & _
" warn: console.warn," & @CRLF & _
" info: console.info" & @CRLF & _
" };" & @CRLF & _
"" & @CRLF & _
" const createWrappedConsole = (type) => {" & @CRLF & _
" return function() {" & @CRLF & _
" // Send to AutoIt" & @CRLF & _
" dispatchToAutoIt({" & @CRLF & _
" type: ""CONSOLE_LOG""," & @CRLF & _
" level: type.toUpperCase()," & @CRLF & _
" message: Array.from(arguments).map(arg => " & @CRLF & _
" (typeof arg === 'object') ? JSON.stringify(arg) : String(arg)" & @CRLF & _
" ).join(' ')," & @CRLF & _
" timestamp: new Date().toISOString()" & @CRLF & _
" });" & @CRLF & _
" // Keep original browser behavior" & @CRLF & _
" originalConsole[type].apply(console, arguments);" & @CRLF & _
" };" & @CRLF & _
" };" & @CRLF & _
"" & @CRLF & _
" // Replace standard console methods" & @CRLF & _
" console.log = createWrappedConsole('log');" & @CRLF & _
" console.error = createWrappedConsole('error');" & @CRLF & _
" console.warn = createWrappedConsole('warn');" & @CRLF & _
" console.info = createWrappedConsole('info');" & @CRLF & _
"" & @CRLF & _
" /**" & @CRLF & _
" * 2. Global Runtime Error Handler" & @CRLF & _
" */" & @CRLF & _
" window.onerror = function(message, source, lineno, colno, error) {" & @CRLF & _
" dispatchToAutoIt({" & @CRLF & _
" type: ""JS_ERROR""," & @CRLF & _
" message: message," & @CRLF & _
" source: source," & @CRLF & _
" line: lineno," & @CRLF & _
" column: colno," & @CRLF & _
" stack: error ? error.stack : """"" & @CRLF & _
" });" & @CRLF & _
" return false; // Let browser handle it as well" & @CRLF & _
" };" & @CRLF & _
"" & @CRLF & _
" // Signal that bridge is active" & @CRLF & _
" dispatchToAutoIt({ type: ""SYSTEM"", message: ""Core Bridge Injected"" });" & @CRLF & _
"})();"
Return $sJS
EndFunc ;==>__Get_Core_Bridge_JS
#EndRegion ; NetWebView2Lib UDF - #INTERNAL_USE_ONLY#

#Region ; NetWebView2Lib UDF - === EVENT HANDLERS ===
Expand Down Expand Up @@ -924,3 +1019,5 @@ Func __NetWebView2_WebViewEvents__OnContextMenu($sMenuData)
__NetWebView2_Log(@ScriptLineNumber, $s_Prefix, 1)
EndFunc ;==>__NetWebView2_WebViewEvents__OnContextMenu
#EndRegion ; NetWebView2Lib UDF - === EVENT HANDLERS ===


50 changes: 50 additions & 0 deletions examples/8-JavaScript.au3
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
#include "..\NetWebView2Lib.au3"

Global $oWebV2M, $oBridge

_Example_Console_Redirect()

Func _Example_Console_Redirect()
Local $hGUI = GUICreate("Console Redirect Test", 400, 300)

; 1. Initialize WebView2
; Initialize WebView2 Manager and register events
Local $oWebV2M = _NetWebView2_CreateManager("Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/144.0.0.0 Safari/537.36 Edg/144.0.0.0", "__MyEVENTS_Manager_", "--disable-gpu, --mute-audio")
$_g_oWeb = $oWebV2M
If @error Then Return SetError(@error, @extended, $oWebV2M)

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

; initialize browser - put it on the GUI
Local $sProfileDirectory = @TempDir & "\NetWebView2Lib-UserDataFolder"
_NetWebView2_Initialize($oWebV2M, $hGUI, $sProfileDirectory, 0, 0, 0, 0, True, True, True, 1.2, "0x2B2B2B", True)
GUISetState(@SW_SHOW)

; navigate to the page
_NetWebView2_Navigate($oWebV2M, "about:blank")

; 6. TEST: Execute a console.log
; Note: We don't use ExecuteScriptWithResult here because
; the data will come back through the Bridge Event!
$oWebV2M.ExecuteScript("console.log('Hello from JavaScript to AutoIt Console!');")
$oWebV2M.ExecuteScript("console.error('This is a test error message');")

While GUIGetMsg() <> -3
WEnd

_NetWebView2_CleanUp($oWebV2M, $oBridge)
EndFunc

; This function handles the incoming messages from the JS Bridge
Func BridgeEvents_OnMessageReceived($sMsg)
; Check if it's a JSON message from our Bridge
If StringLeft($sMsg, 1) = "{" Then
; For simplicity in this example, we just print the raw message
; In a real app, you would parse the JSON to get .message and .level
ConsoleWrite(">>> BRIDGE MESSAGE: " & $sMsg & @CRLF)
EndIf
EndFunc