Skip to content

Commit 8522db4

Browse files
authored
Merge pull request #56 from mlipok/__Get_Core_Bridge_JS
Get core bridge js
2 parents c9de980 + c1eebb9 commit 8522db4

2 files changed

Lines changed: 151 additions & 4 deletions

File tree

NetWebView2Lib.au3

Lines changed: 101 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -67,9 +67,7 @@ Global Enum _ ; $NETWEBVIEW2_MESSAGE__* are set by __NetWebView2_WebViewEvents__
6767
; #FUNCTION# ====================================================================================================================
6868
; Name ..........: _NetWebView2_Initialize
6969
; Description ...:
70-
; Syntax ........: _NetWebView2_Initialize(ByRef $oWebV2M, $hGUI, $sProfileDirectory[, $i_Left = 0[, $i_Top = 0[, $i_Width = 0[,
71-
; $i_Height = 0[, $b_LoadWait = True[, $b_SetAutoResize = True[, $b_AreDevToolsEnabled = True[,
72-
; $i_ZoomFactor = 1.0[, $s_BackColor = "0x2B2B2B"]]]]]]]]])
70+
; 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]]]]]]]]]])
7371
; Parameters ....: $oWebV2M - [in/out] an object.
7472
; $hGUI - a handle value.
7573
; $sProfileDirectory - a string value.
@@ -82,6 +80,7 @@ Global Enum _ ; $NETWEBVIEW2_MESSAGE__* are set by __NetWebView2_WebViewEvents__
8280
; $b_AreDevToolsEnabled- [optional] a boolean value. Default is True.
8381
; $i_ZoomFactor - [optional] an integer value. Default is 1.0.
8482
; $s_BackColor - [optional] a string value. Default is "0x2B2B2B".
83+
; $bInitializeConsoleBridge- [optional] a boolean value. Default is False.
8584
; Return values .: None
8685
; Author ........: mLipok, ioa747
8786
; Modified ......:
@@ -90,7 +89,7 @@ Global Enum _ ; $NETWEBVIEW2_MESSAGE__* are set by __NetWebView2_WebViewEvents__
9089
; Link ..........:
9190
; Example .......: No
9291
; ===============================================================================================================================
93-
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")
92+
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)
9493
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
9594

9695
; ⚠️ Important: Enclose ($hGUI) in parentheses to force "Pass-by-Value".
@@ -107,6 +106,11 @@ Func _NetWebView2_Initialize(ByRef $oWebV2M, $hGUI, $sProfileDirectory, $i_Left
107106
$oWebV2M.AreDevToolsEnabled = $b_AreDevToolsEnabled ; Allow F12
108107
$oWebV2M.ZoomFactor = $i_ZoomFactor
109108
$oWebV2M.BackColor = $s_BackColor
109+
110+
If $bInitializeConsoleBridge Then
111+
$oWebV2M.AddInitializationScript(__Get_Core_Bridge_JS())
112+
EndIf
113+
110114
If @error Then __NetWebView2_Log(@ScriptLineNumber, $s_Prefix & " Manager Creation ERROR", 1)
111115
Return SetError(@error, $oWebV2M.GetBrowserProcessId(), '')
112116
EndFunc ;==>_NetWebView2_Initialize
@@ -167,6 +171,7 @@ Func _NetWebView2_GetBridge(ByRef $oWebV2M, $s_fnEventPrefix = "")
167171

168172
If $s_fnEventPrefix Then $_g_sNetWebView2_User_JSEvents = $s_fnEventPrefix
169173
ObjEvent($oWebJS, "__NetWebView2_JSEvents__", "IBridgeEvents")
174+
170175
Return SetError(@error, @extended, $oWebJS)
171176
EndFunc ;==>_NetWebView2_GetBridge
172177

@@ -616,6 +621,96 @@ Func __NetWebView2_ObjName_FlagsValue(ByRef $oObj)
616621

617622
ConsoleWrite($sInfo & @CRLF)
618623
EndFunc ;==>__NetWebView2_ObjName_FlagsValue
624+
625+
; #INTERNAL_USE_ONLY# ===========================================================================================================
626+
; Name ..........: __Get_Core_Bridge_JS
627+
; Description ...: Get JavaScript for Bridge
628+
; Syntax ........: __Get_Core_Bridge_JS()
629+
; Parameters ....: None
630+
; Return values .: JavaScript for Bridge
631+
; Author ........: ioa747
632+
; Modified ......: mLipok
633+
; Remarks .......:
634+
; Related .......:
635+
; Link ..........:
636+
; Example .......: No
637+
; ===============================================================================================================================
638+
Func __Get_Core_Bridge_JS()
639+
Local $sJS = _
640+
"/**" & @CRLF & _
641+
" * NetWebView2Lib Core Bridge" & @CRLF & _
642+
" * Handles Console Hijacking and Global Error Reporting" & @CRLF & _
643+
" */" & @CRLF & _
644+
"" & @CRLF & _
645+
"(function() {" & @CRLF & _
646+
" // 1. Configuration & State" & @CRLF & _
647+
" window.NET_BRIDGE_ENABLED = true;" & @CRLF & _
648+
"" & @CRLF & _
649+
" /**" & @CRLF & _
650+
" * Centralized message dispatcher to AutoIt" & @CRLF & _
651+
" */" & @CRLF & _
652+
" const dispatchToAutoIt = (data) => {" & @CRLF & _
653+
" try {" & @CRLF & _
654+
" if (window.chrome && window.chrome.webview) {" & @CRLF & _
655+
" window.chrome.webview.postMessage(JSON.stringify(data));" & @CRLF & _
656+
" }" & @CRLF & _
657+
" } catch (e) {" & @CRLF & _
658+
" // Silent fail if bridge is not fully ready" & @CRLF & _
659+
" }" & @CRLF & _
660+
" };" & @CRLF & _
661+
"" & @CRLF & _
662+
" /**" & @CRLF & _
663+
" * Console Hijacking Logic" & @CRLF & _
664+
" */" & @CRLF & _
665+
" const originalConsole = {" & @CRLF & _
666+
" log: console.log," & @CRLF & _
667+
" error: console.error," & @CRLF & _
668+
" warn: console.warn," & @CRLF & _
669+
" info: console.info" & @CRLF & _
670+
" };" & @CRLF & _
671+
"" & @CRLF & _
672+
" const createWrappedConsole = (type) => {" & @CRLF & _
673+
" return function() {" & @CRLF & _
674+
" // Send to AutoIt" & @CRLF & _
675+
" dispatchToAutoIt({" & @CRLF & _
676+
" type: ""CONSOLE_LOG""," & @CRLF & _
677+
" level: type.toUpperCase()," & @CRLF & _
678+
" message: Array.from(arguments).map(arg => " & @CRLF & _
679+
" (typeof arg === 'object') ? JSON.stringify(arg) : String(arg)" & @CRLF & _
680+
" ).join(' ')," & @CRLF & _
681+
" timestamp: new Date().toISOString()" & @CRLF & _
682+
" });" & @CRLF & _
683+
" // Keep original browser behavior" & @CRLF & _
684+
" originalConsole[type].apply(console, arguments);" & @CRLF & _
685+
" };" & @CRLF & _
686+
" };" & @CRLF & _
687+
"" & @CRLF & _
688+
" // Replace standard console methods" & @CRLF & _
689+
" console.log = createWrappedConsole('log');" & @CRLF & _
690+
" console.error = createWrappedConsole('error');" & @CRLF & _
691+
" console.warn = createWrappedConsole('warn');" & @CRLF & _
692+
" console.info = createWrappedConsole('info');" & @CRLF & _
693+
"" & @CRLF & _
694+
" /**" & @CRLF & _
695+
" * 2. Global Runtime Error Handler" & @CRLF & _
696+
" */" & @CRLF & _
697+
" window.onerror = function(message, source, lineno, colno, error) {" & @CRLF & _
698+
" dispatchToAutoIt({" & @CRLF & _
699+
" type: ""JS_ERROR""," & @CRLF & _
700+
" message: message," & @CRLF & _
701+
" source: source," & @CRLF & _
702+
" line: lineno," & @CRLF & _
703+
" column: colno," & @CRLF & _
704+
" stack: error ? error.stack : """"" & @CRLF & _
705+
" });" & @CRLF & _
706+
" return false; // Let browser handle it as well" & @CRLF & _
707+
" };" & @CRLF & _
708+
"" & @CRLF & _
709+
" // Signal that bridge is active" & @CRLF & _
710+
" dispatchToAutoIt({ type: ""SYSTEM"", message: ""Core Bridge Injected"" });" & @CRLF & _
711+
"})();"
712+
Return $sJS
713+
EndFunc ;==>__Get_Core_Bridge_JS
619714
#EndRegion ; NetWebView2Lib UDF - #INTERNAL_USE_ONLY#
620715

621716
#Region ; NetWebView2Lib UDF - === EVENT HANDLERS ===
@@ -924,3 +1019,5 @@ Func __NetWebView2_WebViewEvents__OnContextMenu($sMenuData)
9241019
__NetWebView2_Log(@ScriptLineNumber, $s_Prefix, 1)
9251020
EndFunc ;==>__NetWebView2_WebViewEvents__OnContextMenu
9261021
#EndRegion ; NetWebView2Lib UDF - === EVENT HANDLERS ===
1022+
1023+

examples/8-JavaScript.au3

Lines changed: 50 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,50 @@
1+
#include "..\NetWebView2Lib.au3"
2+
3+
Global $oWebV2M, $oBridge
4+
5+
_Example_Console_Redirect()
6+
7+
Func _Example_Console_Redirect()
8+
Local $hGUI = GUICreate("Console Redirect Test", 400, 300)
9+
10+
; 1. Initialize WebView2
11+
; Initialize WebView2 Manager and register events
12+
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")
13+
$_g_oWeb = $oWebV2M
14+
If @error Then Return SetError(@error, @extended, $oWebV2M)
15+
16+
; create JavaScript Bridge object
17+
Local $oJSBridge = _NetWebView2_GetBridge($oWebV2M, "BridgeEvents_")
18+
#forceref $oJSBridge
19+
If @error Then Return SetError(@error, @extended, $oWebV2M)
20+
21+
; initialize browser - put it on the GUI
22+
Local $sProfileDirectory = @TempDir & "\NetWebView2Lib-UserDataFolder"
23+
_NetWebView2_Initialize($oWebV2M, $hGUI, $sProfileDirectory, 0, 0, 0, 0, True, True, True, 1.2, "0x2B2B2B", True)
24+
GUISetState(@SW_SHOW)
25+
26+
; navigate to the page
27+
_NetWebView2_Navigate($oWebV2M, "about:blank")
28+
29+
; 6. TEST: Execute a console.log
30+
; Note: We don't use ExecuteScriptWithResult here because
31+
; the data will come back through the Bridge Event!
32+
$oWebV2M.ExecuteScript("console.log('Hello from JavaScript to AutoIt Console!');")
33+
$oWebV2M.ExecuteScript("console.error('This is a test error message');")
34+
35+
While GUIGetMsg() <> -3
36+
WEnd
37+
38+
_NetWebView2_CleanUp($oWebV2M, $oBridge)
39+
EndFunc
40+
41+
; This function handles the incoming messages from the JS Bridge
42+
Func BridgeEvents_OnMessageReceived($sMsg)
43+
; Check if it's a JSON message from our Bridge
44+
If StringLeft($sMsg, 1) = "{" Then
45+
; For simplicity in this example, we just print the raw message
46+
; In a real app, you would parse the JSON to get .message and .level
47+
ConsoleWrite(">>> BRIDGE MESSAGE: " & $sMsg & @CRLF)
48+
EndIf
49+
EndFunc
50+

0 commit comments

Comments
 (0)