-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathNetWebView2Lib.au3
More file actions
2432 lines (2179 loc) · 132 KB
/
NetWebView2Lib.au3
File metadata and controls
2432 lines (2179 loc) · 132 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#include-once
#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
#Au3Stripper_Ignore_Funcs=__NetWebView2_Events__*,__NetWebView2_JSEvents__*
#Tidy_Parameters=/tcb=-1
; NetWebView2Lib.au3 - Script Version: 2026.2.25.11 🚩
#include <Array.au3>
#include <GUIConstantsEx.au3>
#include <SendMessage.au3>
#include <StaticConstants.au3>
#include <StringConstants.au3>
#include <MsgBoxConstants.au3>
#include <WinAPIGdi.au3>
#include <WinAPIShPath.au3>
#include <WinAPISysWin.au3>
#include <WindowsConstants.au3>
#REMARK This UDF is marked as WorkInProgress - you may use them, but do not blame me if I do ScriptBreakingChange and as so far do not ask me for description or help till I remove this remark ; mLipok
#TODO UDF HEADER - anybody - feel free to make it done - just do not hesitate to full fill this part
#TODO UDF INDEX - anybody - feel free to make it done - just do not hesitate to full fill this part
#TODO FUNCTION HEADERS SUPLEMENTATION & CHECK - anybody - feel free to make it done - just do not hesitate to full fill this part
#INFO JScript related to WebView2 that we can learn from ; https://github.com/MicrosoftEdge/WebView2Browser/tree/main/wvbrowser_ui
; Global objects
Global $_g_bNetWebView2_DebugInfo = True
;~ Global $_g_bNetWebView2_DebugDev = False
Global $_g_bNetWebView2_DebugDev = (@Compiled = 1)
Global $_g_bNetWebView2_Sleep = Sleep ; Default to calling standard Sleep function
#Region ; === NetWebView2Lib UDF === ENUMS
;~ Global Enum _
;~ $NETWEBVIEW2_ERR__INIT_FAILED, _
;~ $NETWEBVIEW2_ERR__PROFILE_NOT_READY, _
;~ $NETWEBVIEW2_ERR___FAKE_COUNTER
Global Enum _ ; $NETWEBVIEW2_MESSAGE__* are set by mainly by __NetWebView2_Events__OnMessageReceived() but also others
$NETWEBVIEW2_MESSAGE__NONE, _ ; UDF setting - not related directly to API REFERENCES
$NETWEBVIEW2_MESSAGE__INIT_FAILED, _
$NETWEBVIEW2_MESSAGE__PROFILE_NOT_READY, _
$NETWEBVIEW2_MESSAGE__INIT_READY, _
$NETWEBVIEW2_MESSAGE__NAV_STARTING, _
$NETWEBVIEW2_MESSAGE__URL_CHANGED, _
$NETWEBVIEW2_MESSAGE__HISTORY_CHANGED, _ ; #TODO https://learn.microsoft.com/en-us/microsoft-edge/webview2/get-started/wpf#step-7---navigation-events
$NETWEBVIEW2_MESSAGE__SOURCE_CHANGED, _ ; #TODO https://learn.microsoft.com/en-us/microsoft-edge/webview2/get-started/wpf#step-7---navigation-events
$NETWEBVIEW2_MESSAGE__CONTENT_LOADING, _ ; #TODO https://learn.microsoft.com/en-us/microsoft-edge/webview2/get-started/wpf#step-7---navigation-events
$NETWEBVIEW2_MESSAGE__BASIC_AUTHENTICATION_REQUESTED, _ ; #TODO WHERE THIS SHOULD be Lower/Higher ?
$NETWEBVIEW2_MESSAGE__FRAME_NAV_STARTING, _
$NETWEBVIEW2_MESSAGE__FRAME_NAV_COMPLETED, _
$NETWEBVIEW2_MESSAGE__FRAME_CONTENT_LOADING, _
$NETWEBVIEW2_MESSAGE__FRAME_DOM_CONTENT_LOADED, _
$NETWEBVIEW2_MESSAGE__FRAME_WEB_MESSAGE_RECEIVED, _
$NETWEBVIEW2_MESSAGE__FRAME_HTML_SOURCE, _
$NETWEBVIEW2_MESSAGE__CRITICAL_ERROR, _
$NETWEBVIEW2_MESSAGE__DOM_CONTENT_LOADED, _ ; #TODO https://learn.microsoft.com/en-us/microsoft-edge/webview2/concepts/navigation-events
$NETWEBVIEW2_MESSAGE__NAV_ERROR, _
$NETWEBVIEW2_MESSAGE__NAV_COMPLETED, _
$NETWEBVIEW2_MESSAGE__PROCESS_FAILED, _
$NETWEBVIEW2_MESSAGE__TITLE_CHANGED, _
$NETWEBVIEW2_MESSAGE__BROWSER_GOT_FOCUS, _
$NETWEBVIEW2_MESSAGE__BROWSER_LOST_FOCUS, _
$NETWEBVIEW2_MESSAGE__WINDOW_RESIZED, _
$NETWEBVIEW2_MESSAGE__ZOOM_CHANGED, _
$NETWEBVIEW2_MESSAGE__EXTENSION, _
$NETWEBVIEW2_MESSAGE__EXTENSION_LOADED, _ ; #TODO Question ? when EXTENSION is loaded ? before $NETWEBVIEW2_MESSAGE__INIT_READY ? before $NETWEBVIEW2_MESSAGE__NAV_COMPLETED ?
$NETWEBVIEW2_MESSAGE__EXTENSION_FAILED, _
$NETWEBVIEW2_MESSAGE__EXTENSION_REMOVED, _
$NETWEBVIEW2_MESSAGE__EXTENSION_NOT_FOUND, _
$NETWEBVIEW2_MESSAGE__REMOVE_EXTENSION_FAILED, _
$NETWEBVIEW2_MESSAGE__SELECTED_TEXT, _
$NETWEBVIEW2_MESSAGE__INNER_TEXT, _
$NETWEBVIEW2_MESSAGE__INNER_TEXT_FAILED, _
$NETWEBVIEW2_MESSAGE__HTML_SOURCE, _
$NETWEBVIEW2_MESSAGE__CAPTURE_SUCCESS, _
$NETWEBVIEW2_MESSAGE__CAPTURE_ERROR, _
$NETWEBVIEW2_MESSAGE__PRINT_ERROR, _
$NETWEBVIEW2_MESSAGE__PDF_EXPORT_SUCCESS, _
$NETWEBVIEW2_MESSAGE__PDF_EXPORT_ERROR, _
$NETWEBVIEW2_MESSAGE__CDP_RESULT, _
$NETWEBVIEW2_MESSAGE__CDP_ERROR, _
$NETWEBVIEW2_MESSAGE__DATA_CLEARED, _
$NETWEBVIEW2_MESSAGE__COOKIES_B64, _
$NETWEBVIEW2_MESSAGE__COOKIES_ERROR, _
$NETWEBVIEW2_MESSAGE__COOKIE_ADD_ERROR, _
$NETWEBVIEW2_MESSAGE__BLOCKED_AD, _
$NETWEBVIEW2_MESSAGE__DOWNLOAD_STARTING, _
$NETWEBVIEW2_MESSAGE__DOWNLOAD_IN_PROGRESS, _
$NETWEBVIEW2_MESSAGE__DOWNLOAD_INTERRUPTED, _
$NETWEBVIEW2_MESSAGE__DOWNLOAD_COMPLETED, _
$NETWEBVIEW2_MESSAGE__RESPONSE_RECEIVED, _
$NETWEBVIEW2_MESSAGE__UNKNOWN_MESSAGE, _
$NETWEBVIEW2_MESSAGE__USER_ABORT, _
$NETWEBVIEW2_MESSAGE___FAKE_COUNTER
Global Enum _
$NETWEBVIEW2_EXECUTEJS_MODE0_FIREANDFORGET, _
$NETWEBVIEW2_EXECUTEJS_MODE1_ASYNC, _
$NETWEBVIEW2_EXECUTEJS_MODE2_RESULT, _
$NETWEBVIEW2_ExecuteJS__FAKE_COUNTER
Global Enum _ ; Indicates the type of process that has failed.
$NETWEBVIEW2_PROCESS_FAILED_KIND_BROWSER_EXITED, _
$NETWEBVIEW2_PROCESS_FAILED_KIND_RENDER_EXITED, _
$NETWEBVIEW2_PROCESS_FAILED_KIND_RENDER_UNRESPONSIVE, _
$NETWEBVIEW2_PROCESS_FAILED_KIND_FRAME_RENDER_EXITED, _
$NETWEBVIEW2_PROCESS_FAILED_KIND_UTILITY_EXITED, _
$NETWEBVIEW2_PROCESS_FAILED_KIND_SANDBOX_EXITED, _
$NETWEBVIEW2_PROCESS_FAILED_KIND_GPU_EXITED
Global Enum _ ; Indicates the reason for the process failure.
$NETWEBVIEW2_PROCESS_FAILED_REASON_UNEXPECTED, _
$NETWEBVIEW2_PROCESS_FAILED_REASON_UNRESPONSIVE, _
$NETWEBVIEW2_PROCESS_FAILED_REASON_TERMINATED, _
$NETWEBVIEW2_PROCESS_FAILED_REASON_CRASHED, _
$NETWEBVIEW2_PROCESS_FAILED_REASON_LAUNCH_FAILED, _
$NETWEBVIEW2_PROCESS_FAILED_REASON_OUT_OF_MEMORY
#EndRegion ; === NetWebView2Lib UDF === ENUMS
#Region ; === NetWebView2Lib UDF === _NetWebView2_* core functions
; #FUNCTION# ====================================================================================================================
; Name ..........: _NetWebView2_CreateManager
; Description ...: Create WebView2 object
; Syntax ........: _NetWebView2_CreateManager([$sUserAgent = ''[, $s_fnEventPrefix = ""[, $s_AddBrowserArgs = ""[,
; $bVerbose = False]]]])
; Parameters ....: $sUserAgent - [optional] a string value. Default is ''.
; $s_fnEventPrefix - [optional] a string value. Default is "".
; $s_AddBrowserArgs - [optional] a string value. Default is "". Allows passing command-line switches (e.g., --disable-gpu, --mute-audio, --proxy-server="...") to the Chromium engine.
; $bVerbose - [optional] True/False - Enable/Disable diagnostic logging. Default is False = Disabled.
; Return values .: None
; Author ........: mLipok, ioa747
; Modified ......:
; Remarks .......: $s_AddBrowserArgs must be set before calling Initialize().
; Related .......:
; Link ..........: https://www.chromium.org/developers/how-tos/run-chromium-with-flags
; Link ..........: https://chromium.googlesource.com/chromium/src/+/main/docs/configuration.md#switches
; Link ..........: https://peter.sh/experiments/chromium-command-line-switches/
; Example .......: No
; ===============================================================================================================================
Func _NetWebView2_CreateManager($sUserAgent = '', $s_fnEventPrefix = "", $s_AddBrowserArgs = "", $bVerbose = False)
Local Const $s_Prefix = "[_NetWebView2_CreateManager]: fnEventPrefix=" & $s_fnEventPrefix & " AddBrowserArgs=" & $s_AddBrowserArgs
Local $oMyError = ObjEvent("AutoIt.Error", __NetWebView2_COMErrFunc) ; Local COM Error Handler
#forceref $oMyError
Local $oWebV2M = ObjCreate("NetWebView2Lib.WebView2Manager") ; REGISTERED VERSION
If @error Then __NetWebView2_Log(@ScriptLineNumber, $s_Prefix & " Manager Creation ERROR", 1)
If @error Then Return SetError(@error, @extended, 0)
; Enable/Disable diagnostic logging
; When enabled, the console will show entries like: +++[NetWebView2Lib][HANDLE:0x...][HH:mm:ss.fff] Message
; Verbose property was added to allow real-time diagnostic logging to the SciTE console (or any stdout listener).
; The diagnostic logs use a distinctive prefix and include the instance handle for easier filtering in multi-window applications.
$oWebV2M.Verbose = $bVerbose
;~ If $_g_bNetWebView2_DebugDev Then __NetWebView2_ObjName_FlagsValue($oWebV2M) ; FOR DEV TESTING ONLY
If $sUserAgent Then $oWebV2M.SetUserAgent($sUserAgent)
If $s_AddBrowserArgs Then $oWebV2M.AdditionalBrowserArguments = $s_AddBrowserArgs
ObjEvent($oWebV2M, "__NetWebView2_Events__", "IWebViewEvents")
If $s_fnEventPrefix Then ObjEvent($oWebV2M, $s_fnEventPrefix, "IWebViewEvents")
Return SetError(@error, @extended, $oWebV2M)
EndFunc ;==>_NetWebView2_CreateManager
; #FUNCTION# ====================================================================================================================
; Name ..........: _NetWebView2_Initialize
; Description ...:
; Syntax ........: _NetWebView2_Initialize($oWebV2M, $hUserGUI, $s_ProfileDirectory[, $i_Left = 0[, $i_Top = 0[, $i_Width = 0[,
; $i_Height = 0[, $b_SetAutoResize = True[, $b_DevToolsEnabled = True[, $i_ZoomFactor = 1.0[,
; $s_BackColor = "0x2B2B2B"[, $b_InitConsole = False]]]]]]]]])
; Parameters ....: $oWebV2M - an object.
; $hUserGUI - a handle to User window in which new WebView Window containng the controler should be placed/added
; $s_ProfileDirectory - a string value.
; $i_Left - [optional] an integer value. Default is 0.
; $i_Top - [optional] an integer value. Default is 0.
; $i_Width - [optional] an integer value. Default is 0.
; $i_Height - [optional] an integer value. Default is 0.
; $b_SetAutoResize - [optional] a boolean value. Default is True.
; $b_DevToolsEnabled - [optional] a boolean value. Default is True. Allow F12 to show Developer Tools in WebView2 component
; $i_ZoomFactor - [optional] an integer value. Default is 1.0.
; $s_BackColor - [optional] a string value. Default is "0x2B2B2B".
; $b_InitConsole - [optional] a boolean value. Default is False.
; Return values .: $iInit
; Author ........: mLipok, ioa747
; Modified ......:
; Remarks .......:
; Related .......:
; Link ..........:
; Example .......: No
; ===============================================================================================================================
Func _NetWebView2_Initialize($oWebV2M, $hUserGUI, $s_ProfileDirectory, $i_Left = 0, $i_Top = 0, $i_Width = 0, $i_Height = 0, $b_SetAutoResize = True, $b_DevToolsEnabled = True, $i_ZoomFactor = 1.0, $s_BackColor = "0x2B2B2B", $b_InitConsole = False)
Local Const $s_Prefix = "[_NetWebView2_Initialize]: GUI:" & $hUserGUI & " ProfileDirectory:" & $s_ProfileDirectory & " LEFT:" & $i_Left & " TOP:" & $i_Top & " WIDTH" & $i_Width & " HEIGHT:" & $i_Height & " SETAUTORESIZE:" & $b_SetAutoResize & " SetAutoResize:" & $b_DevToolsEnabled & " ZoomFactor:" & $i_ZoomFactor & " BackColor:" & $s_BackColor
Local $oMyError = ObjEvent("AutoIt.Error", __NetWebView2_COMErrFunc) ; Local COM Error Handler
#forceref $oMyError
If Not IsHWnd($hUserGUI) Then
__NetWebView2_Log(@ScriptLineNumber, $s_Prefix & " !!! ERROR: $hUserGUI is not a valid HWND pointer.", 1)
Return SetError($NETWEBVIEW2_MESSAGE__CRITICAL_ERROR, 0, False)
EndIf
; ⚠️ Important: Enclose ($hUserGUI) in parentheses to force "Pass-by-Value".
; This prevents the COM layer from changing the AutoIt variable type from Ptr to Int64.
Local $iInit = $oWebV2M.Initialize(($hUserGUI), $s_ProfileDirectory, $i_Left, $i_Top, $i_Width, $i_Height)
If @error Then Return SetError(@error, @extended, $iInit)
If $_g_bNetWebView2_DebugDev Then ConsoleWrite("! IFNC: FailureReportFolderPath = " & $oWebV2M.FailureReportFolderPath & @CRLF)
#Region ; After Initialization wait for the engine to be ready before navigating
Local $hTimer = TimerInit()
Local $iTimeOut_ms = 10000 ; max 10 seconds for initialization
Local $iMessage
Do
__NetWebView2_Sleep(10)
If @error Then Return SetError(@error, @extended, '')
$iMessage = __NetWebView2_LastMessage_KEEPER($oWebV2M)
If $iMessage = $NETWEBVIEW2_MESSAGE__INIT_FAILED _
Or $iMessage = $NETWEBVIEW2_MESSAGE__PROFILE_NOT_READY _
Or $iMessage = $NETWEBVIEW2_MESSAGE__PROCESS_FAILED _
Or $iMessage = $NETWEBVIEW2_MESSAGE__CRITICAL_ERROR Then
Return SetError($iMessage, @extended, '')
EndIf
If TimerDiff($hTimer) >= $iTimeOut_ms Then Return SetError(1, 0, '')
Until $oWebV2M.IsReady Or $iMessage = $NETWEBVIEW2_MESSAGE__INIT_READY
;~ If Not __NetWebView2_WaitForReadyState($oWebV2M, $hTimer, $iTimeOut_ms) Then Return SetError(2, 0, '')
#EndRegion ; After Initialization wait for the engine to be ready before navigating
; WebView2 Configuration
$oWebV2M.SetAutoResize($b_SetAutoResize) ; Using SetAutoResize(True) to skip WM_SIZE
$oWebV2M.AreDevToolsEnabled = $b_DevToolsEnabled ; Allow F12
$oWebV2M.ZoomFactor = $i_ZoomFactor
$oWebV2M.BackColor = $s_BackColor
If $b_InitConsole 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(), $iInit)
EndFunc ;==>_NetWebView2_Initialize
; #FUNCTION# ====================================================================================================================
; Name ..........: _NetWebView2_IsRegisteredCOMObject
; Description ...: Check if all necessary object are registerd
; Syntax ........: _NetWebView2_IsRegisteredCOMObject()
; Parameters ....: None
; Return values .: True or False
; Author ........: mLipok
; Modified ......:
; Remarks .......:
; Related .......: __NetWebView2_fake_COMErrFunc
; Link ..........:
; Example .......: No
; ===============================================================================================================================
Func _NetWebView2_IsRegisteredCOMObject()
Local $oMyError = ObjEvent("AutoIt.Error", __NetWebView2_fake_COMErrFunc) ; Local COM Error Handler
#forceref $oMyError
ObjCreate("NetWebView2Lib.WebView2Manager")
If @error Then Return SetError(1, 0, False)
ObjCreate("NetWebView2Lib.WebView2Parser")
If @error Then Return SetError(2, 0, False)
Return True
EndFunc ;==>_NetWebView2_IsRegisteredCOMObject
; #FUNCTION# ====================================================================================================================
; Name ..........: _NetWebView2_IsAlreadyInstalled
; Description ...: Check if MS WebView2 is installed or not
; Syntax ........: _NetWebView2_IsAlreadyInstalled()
; Parameters ....: None
; Return values .: True or False
; Author ........: mLipok
; Modified ......:
; Remarks .......:
; Related .......:
; Link ..........: https://learn.microsoft.com/pl-pl/microsoft-edge/webview2/concepts/distribution?tabs=dotnetcsharp#detect-if-a-webview2-runtime-is-already-installed
; Example .......: No
; ===============================================================================================================================
Func _NetWebView2_IsAlreadyInstalled()
Local $sResult, $iExtended = 0
If @AutoItX64 Then
$sResult = RegRead('HKEY_LOCAL_MACHINE\SOFTWARE\WOW6432Node\Microsoft\EdgeUpdate\Clients\{F3017226-FE2A-4295-8BDF-00C3A9A7E4C5}', 'pv')
Else
$sResult = RegRead('HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\EdgeUpdate\Clients\{F3017226-FE2A-4295-8BDF-00C3A9A7E4C5}', 'pv')
EndIf
If $sResult Then
$iExtended = 1
Else
$sResult = RegRead('HKEY_CURRENT_USER\Software\Microsoft\EdgeUpdate\Clients\{F3017226-FE2A-4295-8BDF-00C3A9A7E4C5}', 'pv')
$iExtended = 2
EndIf
If @AutoItX64 Then $iExtended += 10
Return SetError(($sResult = ''), $iExtended, $sResult)
#cs The two registry locations to inspect on 64-bit Windows: https://learn.microsoft.com/pl-pl/microsoft-edge/webview2/concepts/distribution?tabs=dotnetcsharp#detect-if-a-webview2-runtime-is-already-installed
HKEY_LOCAL_MACHINE\SOFTWARE\WOW6432Node\Microsoft\EdgeUpdate\Clients\{F3017226-FE2A-4295-8BDF-00C3A9A7E4C5}
HKEY_CURRENT_USER\Software\Microsoft\EdgeUpdate\Clients\{F3017226-FE2A-4295-8BDF-00C3A9A7E4C5}
#ce The two registry locations to inspect on 64-bit Windows: https://learn.microsoft.com/pl-pl/microsoft-edge/webview2/concepts/distribution?tabs=dotnetcsharp#detect-if-a-webview2-runtime-is-already-installed
#cs The two registry locations to inspect on 32-bit Windows: https://learn.microsoft.com/pl-pl/microsoft-edge/webview2/concepts/distribution?tabs=dotnetcsharp#detect-if-a-webview2-runtime-is-already-installed
HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\EdgeUpdate\Clients\{F3017226-FE2A-4295-8BDF-00C3A9A7E4C5}
HKEY_CURRENT_USER\Software\Microsoft\EdgeUpdate\Clients\{F3017226-FE2A-4295-8BDF-00C3A9A7E4C5}
#CE The two registry locations to inspect on 32-bit Windows: https://learn.microsoft.com/pl-pl/microsoft-edge/webview2/concepts/distribution?tabs=dotnetcsharp#detect-if-a-webview2-runtime-is-already-installed
EndFunc ;==>_NetWebView2_IsAlreadyInstalled
; #FUNCTION# ====================================================================================================================
; Name ..........: _NetWebView2_CleanUp
; Description ...:
; Syntax ........: _NetWebView2_CleanUp(ByRef $oWebV2M, ByRef $oJSBridge)
; Parameters ....: $oWebV2M - [in/out] an object.
; $oJSBridge - [in/out] an object.
; Return values .: None
; Author ........: mLipok, ioa747
; Modified ......:
; Remarks .......:
; Related .......:
; Link ..........:
; Example .......: No
; ===============================================================================================================================
Func _NetWebView2_CleanUp(ByRef $oWebV2M, ByRef $oJSBridge)
Local Const $s_Prefix = "[_NetWebView2_CleanUp]:"
Local $oMyError = ObjEvent("AutoIt.Error", __NetWebView2_COMErrFunc) ; Local COM Error Handler
#forceref $oMyError
If (Not IsObj($oWebV2M)) Or ObjName($oWebV2M, $OBJ_PROGID) <> 'NetWebView2Lib.WebView2Manager' Then Return SetError(1, 0, __NetWebView2_Log(@ScriptLineNumber, $s_Prefix & " ! Object not found", 1))
_NetWebView2_SetLockState($oWebV2M, True)
Local $iRet = $oWebV2M.Cleanup()
If @error Then __NetWebView2_Log(@ScriptLineNumber, $s_Prefix & " ! Error during internal cleanup", 1)
$oWebV2M = 0
$oJSBridge = 0
If @error Then __NetWebView2_Log(@ScriptLineNumber, $s_Prefix, 1)
; Update Static Map to delete Handle
__NetWebView2_LastMessage_KEEPER($oWebV2M, -1)
Return SetError(@error, @extended, $iRet)
EndFunc ;==>_NetWebView2_CleanUp
; #FUNCTION# ====================================================================================================================
; Name ..........: _NetWebView2_ExecuteScript
; Description ...:
; Syntax ........: _NetWebView2_ExecuteScript($oWebV2M, $sJavaScript[, $iMode = 0])
; Parameters ....: $oWebV2M - an object.
; $sJavaScript - a string value.
; $iMode - [optional] Default is $NETWEBVIEW2_EXECUTEJS_MODE0_FIREANDFORGET. One of the following search modes:
; |0 - $NETWEBVIEW2_EXECUTEJS_MODE0_FIREANDFORGET - Execute, do not wait "Fire-and-Forget"
; |1 - $NETWEBVIEW2_EXECUTEJS_MODE1_ASYNC - ExecuteScriptOnPage "Async-Void Trap"
; |2 - $NETWEBVIEW2_EXECUTEJS_MODE2_RESULT - ExecuteScriptWithResult - This is the only method designed to return data
; Return values .: None
; Author ........: mLipok, ioa747
; Modified ......:
; Remarks .......: $iMode additionall information:
; $NETWEBVIEW2_EXECUTEJS_MODE0_FIREANDFORGET - ExecuteScript (Fire-and-Forget)
; In the C# bridge, this is defined as a public void. It uses _webView.Invoke to send the command to the UI thread and exits immediately. It does not wait for the JavaScript to execute, and it has no return type.
; Use case: Clicking buttons, scrolling, or triggering JS events where you don't care about the result.
; $NETWEBVIEW2_EXECUTEJS_MODE1_ASYNC - ExecuteScriptOnPage (Async-Void Trap)
; This is defined as public async void. In COM Interop (which AutoIt uses), an async void method returns control to the caller (AutoIt) the moment it hits the first internal await. The script runs in the background, but the result is never passed back to the COM interface.
; Use case: Fast execution where background processing is acceptable, but again, no return value.
; $NETWEBVIEW2_EXECUTEJS_MODE2_RESULT - ExecuteScriptWithResult
; This is the only method designed to return data. It implements a Message Pump (using Application.DoEvents()) to keep the interface responsive while waiting up to 5 seconds for the result.
; Key Features of ExecuteScriptWithResult:
; Blocking: It waits for the script to finish (Sync-like behavior for AutoIt).
; JSON Cleaning: WebView2 returns results as JSON strings (e.g., "Hello"). This method automatically strips the extra quotes and unescapes the string for you.
; Error Handling: Returns ERROR: Script Timeout if the JS takes longer than 5 seconds.
; Related .......:
; Link ..........: https://github.com/ioa747/NetWebView2Lib/issues/45#issuecomment-3831184514
; Example .......: No
; ===============================================================================================================================
Func _NetWebView2_ExecuteScript($oWebV2M, $sJavaScript, $iMode = $NETWEBVIEW2_EXECUTEJS_MODE0_FIREANDFORGET)
Local Const $s_Prefix = "[_NetWebView2_ExecuteScript]:" & " TYPE: " & $iMode
Local $oMyError = ObjEvent("AutoIt.Error", __NetWebView2_COMErrFunc) ; Local COM Error Handler
#forceref $oMyError
Local $iRet
Switch $iMode
Case 0
$iRet = $oWebV2M.ExecuteScript($sJavaScript)
Case 1
$iRet = $oWebV2M.ExecuteScriptOnPage($sJavaScript)
Case 2
$iRet = $oWebV2M.ExecuteScriptWithResult($sJavaScript)
EndSwitch
If @error Then __NetWebView2_Log(@ScriptLineNumber, $s_Prefix, 1)
Return SetError(@error, @extended, $iRet)
EndFunc ;==>_NetWebView2_ExecuteScript
; #FUNCTION# ====================================================================================================================
; Name ..........: _NetWebView2_GetBridge
; Description ...:
; Syntax ........: _NetWebView2_GetBridge($oWebV2M[, $s_fnEventPrefix = ""])
; Parameters ....: $oWebV2M - an object.
; $s_fnEventPrefix - [optional] a string value. Default is "".
; Return values .: None
; Author ........: mLipok, ioa747
; Modified ......:
; Remarks .......:
; Related .......:
; Link ..........:
; Example .......: No
; ===============================================================================================================================
Func _NetWebView2_GetBridge($oWebV2M, $s_fnEventPrefix = "")
Local Const $s_Prefix = "[_NetWebView2_GetBridge]:" & " fnEventPrefix:" & $s_fnEventPrefix
Local $oMyError = ObjEvent("AutoIt.Error", __NetWebView2_COMErrFunc) ; Local COM Error Handler
#forceref $oMyError
Local $oWebJS = $oWebV2M.GetBridge()
If @error Then __NetWebView2_Log(@ScriptLineNumber, $s_Prefix & " : Manager.GetBridge() ERROR", 1)
ObjEvent($oWebJS, "__NetWebView2_JSEvents__", "IBridgeEvents")
If $s_fnEventPrefix Then ObjEvent($oWebJS, $s_fnEventPrefix, "IBridgeEvents")
Return SetError(@error, @extended, $oWebJS)
EndFunc ;==>_NetWebView2_GetBridge
; #FUNCTION# ====================================================================================================================
; Name ..........: _NetWebView2_GetVersion
; Description ...: Get NetWebView2Lib component version number
; Syntax ........: _NetWebView2_GetVersion($oWebV2M)
; Parameters ....: $oWebV2M - an object.
; Return values .: NetWebView2Lib component version number or set @error
; Author ........: mLipok
; Modified ......:
; Remarks .......:
; Related .......:
; Link ..........:
; Example .......: No
; ===============================================================================================================================
Func _NetWebView2_GetVersion($oWebV2M)
Local Const $s_Prefix = "[_NetWebView2_GetVersion]:"
Local $oMyError = ObjEvent("AutoIt.Error", __NetWebView2_COMErrFunc) ; Local COM Error Handler
#forceref $oMyError
Local $sVersion = $oWebV2M.version
__NetWebView2_Log(@ScriptLineNumber, $s_Prefix & " : Version=" & $sVersion, 1)
Return SetError(@error, @extended, $sVersion)
EndFunc ;==>_NetWebView2_GetVersion
; #FUNCTION# ====================================================================================================================
; Name...........: _NetWebView2_LoadWait
; Description....: Waits for a specific WebView2 status or event with a timeout.
; Syntax ........: _NetWebView2_LoadWait($oWebV2M[, $iWaitMessage = $NETWEBVIEW2_MESSAGE__TITLE_CHANGED[, $sExpectedTitle = ""[,
; $iTimeOut_ms = 5000]]])
; Parameters.....: $oWebV2M - The NetWebView2 Manager object.
; $iWaitMessage - The status code to wait for (Default is $NETWEBVIEW2_MESSAGE__TITLE_CHANGED).
; $sExpectedTitle - [optional] Expected title to LoadWait for, as StringRegExp() pattern
; $iTimeOut_ms - [optional] Maximum time to wait in milliseconds. 0 for infinite. Default is 5000ms
; Return values..: Success - True
; Failure - False and sets @error:
; 3 - Navigation Error ($NETWEBVIEW2_MESSAGE__NAV_ERROR)
; 4 - Timeout reached
; Author ........: mLipok, ioa747
; Modified ......:
; Remarks .......: This function uses a centralized state machine to track asynchronous events.
; Related .......:
; Link ..........:
; Example .......: No
; ===============================================================================================================================
Func _NetWebView2_LoadWait($oWebV2M, $iWaitMessage = $NETWEBVIEW2_MESSAGE__TITLE_CHANGED, $sExpectedTitle = "", $iTimeOut_ms = 5000)
Local Const $s_Prefix = '[_NetWebView2_LoadWait]: WaitMessage:' & $iWaitMessage & ' WAIT:' & $iWaitMessage & ' ExpectedTitle="' & $sExpectedTitle & '" TimeOut_ms=' & $iTimeOut_ms
Local $hTimer = TimerInit()
; RESET: Clear the status of this instance before starting the wait loop
__NetWebView2_LastMessage_Navigation($oWebV2M, $NETWEBVIEW2_MESSAGE__NONE)
While 1
; Allow AutoIt to "breathe" and process the GUI messages, also allow user to abort
__NetWebView2_Sleep(10)
If @error Then Return SetError(@error, @extended, '')
; RULE 1: If we reached the target status or higher
Local $bWebIsReady = $oWebV2M.IsReady
If @error Then
__NetWebView2_Log(@ScriptLineNumber, $s_Prefix, 1)
Return SetError(1, 0, False) ; browser/COM error ?
EndIf
; RULE 2: TimeOut Check
If $iTimeOut_ms And TimerDiff($hTimer) >= $iTimeOut_ms Then
__NetWebView2_Log(@ScriptLineNumber, $s_Prefix & " - TIME OUT - the waiting time has expired", 1)
Return SetError(2, 0, False)
EndIf
; RULE 3: if browser is not ready continue waiting
If Not $bWebIsReady Then ContinueLoop ; For navigation events, ensure the browser reports IsReady
; RULE 4: checking browser ReadyState
Local $iLastMessage = -1
Local $sReadyState = _NetWebView2_ExecuteScript($oWebV2M, "document.readyState", $NETWEBVIEW2_EXECUTEJS_MODE2_RESULT)
If @error Then
__NetWebView2_Log(@ScriptLineNumber, $s_Prefix, 1)
Return SetError(7, 0, False)
ElseIf StringLeft($sReadyState, 6) == "ERROR:" Then
__NetWebView2_Log(@ScriptLineNumber, $s_Prefix, 1)
Return SetError(8, 0, False)
ElseIf $sReadyState = "complete" Then
; RULE 5: checking events messages
$iLastMessage = __NetWebView2_LastMessage_Navigation($oWebV2M)
If $_g_bNetWebView2_DebugDev Then ConsoleWrite('! IFNC: TEST LOAD WAIT: ReadyState=' & $sReadyState & ' LastMessage=' & $iLastMessage & ' WaitMessage=' & $iWaitMessage & ' SLN=' & @ScriptLineNumber & @CRLF)
If $iLastMessage = $NETWEBVIEW2_MESSAGE__NAV_ERROR Or $iLastMessage = $NETWEBVIEW2_MESSAGE__PROCESS_FAILED Or $iLastMessage = $NETWEBVIEW2_MESSAGE__CRITICAL_ERROR Then
If $_g_bNetWebView2_DebugDev Then ConsoleWrite('! IFNC: TEST LOAD WAIT: ' & $iLastMessage & ' SLN=' & @ScriptLineNumber & @CRLF)
__NetWebView2_Log(@ScriptLineNumber, $s_Prefix, 1)
Return SetError(3, $iLastMessage, False)
;~ ElseIf $iLastMessage >= $iWaitMessage Then ; checking events
ElseIf $iLastMessage >= $iWaitMessage Then ; checking events
; RULE 6: checking document title
Local $sCurrentTitle = $oWebV2M.GetDocumentTitle()
Local $bTitleCheck = ($sExpectedTitle And StringRegExp($sCurrentTitle, $sExpectedTitle, $STR_REGEXPMATCH) = 1)
Local $s_MessageInfo = '! IFNC: TEST LOAD WAIT: CurrentTitle="' & $sCurrentTitle & '" ExpectedTitle"' & $sExpectedTitle & '" TitleCheck=' & $bTitleCheck & ' LastMessage=' & $iLastMessage
If $sExpectedTitle And $iWaitMessage = $NETWEBVIEW2_MESSAGE__TITLE_CHANGED And $bTitleCheck Then
If $_g_bNetWebView2_DebugDev Then ConsoleWrite($s_MessageInfo & ' SLN=' & @ScriptLineNumber & @CRLF)
__NetWebView2_Log(@ScriptLineNumber, $s_Prefix & " LastMessage=" & $iLastMessage, 1)
Return True
Else
If $_g_bNetWebView2_DebugDev Then ConsoleWrite($s_MessageInfo & ' SLN=' & @ScriptLineNumber & @CRLF)
__NetWebView2_Log(@ScriptLineNumber, $s_Prefix & " LastMessage=" & $iLastMessage, 1)
Return True
EndIf
EndIf
EndIf
If $_g_bNetWebView2_DebugDev Then ConsoleWrite("> IFNC: TEST LOAD WAIT: __NetWebView2_LastMessage_Navigation($oWebV2M)=" & $iLastMessage & ' >> ' & __NetWebView2_LastMessage_Navigation($oWebV2M) & ' SLN=' & @ScriptLineNumber & @CRLF)
WEnd
EndFunc ;==>_NetWebView2_LoadWait
; #FUNCTION# ====================================================================================================================
; Name...........: _NetWebView2_Navigate
; Description....: Navigates to a URL and waits for a specific completion status.
; Syntax ........: _NetWebView2_Navigate($oWebV2M, $s_URL[, $iWaitMessage = $NETWEBVIEW2_MESSAGE__TITLE_CHANGED[,
; $sExpectedTitle = ""[, $iTimeOut_ms = 5000]]])
; Parameters.....: $oWebV2M - The NetWebView2 Manager object.
; $s_URL - The URL to navigate to.
; $iWaitMessage - The status code to wait for (Default is $NETWEBVIEW2_MESSAGE__TITLE_CHANGED).
; $sExpectedTitle - [optional] Expected title to LoadWait for, as StringRegExp() pattern
; $iTimeOut_ms - [optional] Maximum time to wait in milliseconds. 0 for infinite. Default is 5000ms
; Return values..: Success - True
; Failure - False and sets @error:
; 1 - Invalid parameters
; 2 - Navigation call failed (COM error)
; 3 - Navigation Error status received
; 4 - Timeout reached
; Author ........: mLipok, ioa747
; Modified ......:
; Remarks .......:
; Related .......:
; Link ..........:
; Example .......: No
; ===============================================================================================================================
Func _NetWebView2_Navigate($oWebV2M, $s_URL, $iWaitMessage = $NETWEBVIEW2_MESSAGE__TITLE_CHANGED, $sExpectedTitle = "", $iTimeOut_ms = 5000)
Local Const $s_Prefix = "[_NetWebView2_Navigate]: URL:" & $s_URL & " WAIT:" & $iWaitMessage & " TimeOut_ms=" & $iTimeOut_ms
Local $oMyError = ObjEvent("AutoIt.Error", __NetWebView2_COMErrFunc) ; Local COM Error Handler
#forceref $oMyError
If (Not IsObj($oWebV2M)) Or ObjName($oWebV2M, $OBJ_PROGID) <> 'NetWebView2Lib.WebView2Manager' Then Return SetError(1, 0, "ERROR: Invalid Object")
; 1. Parameter Validation
If $iWaitMessage < $NETWEBVIEW2_MESSAGE__INIT_READY Or $iWaitMessage > $NETWEBVIEW2_MESSAGE__TITLE_CHANGED Then ; higher messsages are not for NAVIGATION thus not checking in _NetWebView2_LoadWait()
Return SetError(1, 0, False)
EndIf
; 2. Execute Navigation
; The Local Error Handler catches potential "Disposed Object" crashes here
$oWebV2M.LockWebView()
$oWebV2M.Navigate($s_URL)
If @error Then Return SetError(2, @error, False)
; 3. Wait for status using the Bulletproof LoadWait logic
Local $bResult = _NetWebView2_LoadWait($oWebV2M, $iWaitMessage, $sExpectedTitle, $iTimeOut_ms)
Local $iErr = @error, $iExt = @extended
; If an error occurred (3: Nav Error, 4: Timeout), log the failure
If @error Then
__NetWebView2_Log(@ScriptLineNumber, $s_Prefix & " -> LOAD WAIT FAILED (Err:" & $iErr & " Ext:" & $iExt & ")", 1)
EndIf
$oWebV2M.UnLockWebView()
Return SetError($iErr, $iExt, $bResult)
EndFunc ;==>_NetWebView2_Navigate
; #FUNCTION# ====================================================================================================================
; Name ..........: _NetWebView2_NavigateToString
; Description ...:
; Syntax ........: _NetWebView2_NavigateToString($oWebV2M, $s_HTML[, $iWaitMessage = $NETWEBVIEW2_MESSAGE__TITLE_CHANGED[,
; $sExpectedTitle = ""[, $iTimeOut_ms = 5000]]])
; Parameters ....: $oWebV2M - an object.
; $s_HTML - a string value.
; $iWaitMessage - [optional] an integer value. Default is $NETWEBVIEW2_MESSAGE__TITLE_CHANGED.
; $sExpectedTitle - [optional] Expected title to LoadWait for, as StringRegExp() pattern
; $iTimeOut_ms - [optional] Maximum time to wait in milliseconds. 0 for infinite. Default is 5000ms
; Return values .: None
; Author ........: mLipok, ioa747
; Modified ......:
; Remarks .......:
; Related .......:
; Link ..........:
; Example .......: No
; ===============================================================================================================================
Func _NetWebView2_NavigateToString($oWebV2M, $s_HTML, $iWaitMessage = $NETWEBVIEW2_MESSAGE__TITLE_CHANGED, $sExpectedTitle = "", $iTimeOut_ms = 5000)
Local Const $s_Prefix = "[_NetWebView2_NavigateToString]:" & " HTML Size:" & StringLen($s_HTML) & " WaitMessage:" & $iWaitMessage & " TimeOut_ms=" & $iTimeOut_ms
Local $oMyError = ObjEvent("AutoIt.Error", __NetWebView2_COMErrFunc) ; Local COM Error Handler
#forceref $oMyError
If (Not IsObj($oWebV2M)) Or ObjName($oWebV2M, $OBJ_PROGID) <> 'NetWebView2Lib.WebView2Manager' Then Return SetError(1, 0, "ERROR: Invalid Object")
If $iWaitMessage < $NETWEBVIEW2_MESSAGE__INIT_READY Then
Return SetError(1)
ElseIf $iWaitMessage > $NETWEBVIEW2_MESSAGE__TITLE_CHANGED Then ; higher messsages are not for NAVIGATION thus not checking in _NetWebView2_LoadWait()
Return SetError(2)
Else
$oWebV2M.LockWebView()
Local $iNavigation = $oWebV2M.NavigateToString($s_HTML)
Local $iErr = @error, $iExt = @extended
If @error Then
Return SetError($iErr, $iExt, $iNavigation)
Else
_NetWebView2_LoadWait($oWebV2M, $iWaitMessage, $sExpectedTitle, $iTimeOut_ms)
$iErr = @error
$iExt = @extended
$oWebV2M.UnLockWebView()
If $iErr Then __NetWebView2_Log(@ScriptLineNumber, $s_Prefix, 1, $iErr, $iExt)
Return SetError($iErr, $iExt, $iNavigation)
EndIf
EndIf
EndFunc ;==>_NetWebView2_NavigateToString
#EndRegion ; === NetWebView2Lib UDF === _NetWebView2_* core functions
#Region ; === NetWebView2Lib UDF === _NetWebView2_* helper functions
; #FUNCTION# ====================================================================================================================
; Name ..........: _NetWebView2_BrowserSetupWrapper
; Description ...:
; Syntax ........: _NetWebView2_BrowserSetupWrapper($hOuterParentWindow, ByRef $oOuterWeb, $sEventPrefix, $sProfile,
; ByRef $oOuterBridge, ByRef $hInnerWebViewWindow, $iX, $iY, $iW, $iH, $s_AddBrowserArgs)
; Parameters ....: $hOuterParentWindow - a handle value.
; $oOuterWeb - [in/out] an object.
; $sEventPrefix - a string value.
; $sProfile - a string value.
; $oOuterBridge - [in/out] an object.
; $hInnerWebViewWindow - [in/out] a handle value.
; $iX - an integer value.
; $iY - an integer value.
; $iW - an integer value.
; $iH - an integer value.
; $s_AddBrowserArgs - a string value.
; Return values .: None
; Author ........: ioa747, mLipok
; Modified ......:
; Remarks .......:
; Related .......:
; Link ..........:
; Example .......: No
; ===============================================================================================================================
Func _NetWebView2_BrowserSetupWrapper($hOuterParentWindow, ByRef $oOuterWeb, $sEventPrefix, $sProfile, ByRef $oOuterBridge, ByRef $hInnerWebViewWindow, $iX, $iY, $iW, $iH, $s_AddBrowserArgs)
$hInnerWebViewWindow = GUICreate("", $iW, $iH, $iX, $iY, $WS_CHILD, -1, $hOuterParentWindow)
GUISetState(@SW_SHOW, $hInnerWebViewWindow)
$oOuterWeb = _NetWebView2_CreateManager("", $sEventPrefix & '_Manager__', $s_AddBrowserArgs)
If @error Then Return SetError(@error, @extended, $oOuterWeb)
Local $Result = _NetWebView2_Initialize($oOuterWeb, $hInnerWebViewWindow, $sProfile, 0, 0, $iW, $iH)
If @error Then Return SetError(@error, @extended, $Result)
$oOuterBridge = _NetWebView2_GetBridge($oOuterWeb, $sEventPrefix & "_Bridge__")
If @error Then Return SetError(@error, @extended, $oOuterBridge)
EndFunc ;==>_NetWebView2_BrowserSetupWrapper
; #FUNCTION# ====================================================================================================================
; Name ..........: _NetWebView2_ExportPageData
; Description ...:
; Syntax ........: _NetWebView2_ExportPageData($oWebV2M, $iFormat[, $sFilePath = ''])
; Parameters ....: $oWebV2M - an object.
; $iFormat - a string value. 0 HTML only, 1 MHTML Snapshot
; $sFilePath - [optional] a string value. Default is '' which mean make Base64 as a result instead write to file
; Return values .: Success - Depends on $sFilePath String with Base64 encoded binary content of the PDF or "SUCCESS: File saved to ...."
; Failure - string with error description "ERROR: ........." and set @error to 1
; Author ........: mLipok
; Modified ......:
; Remarks .......:
; Related .......:
; Link ..........:
; Example .......: No
; ===============================================================================================================================
Func _NetWebView2_ExportPageData($oWebV2M, $iFormat, $sFilePath = '')
Local Const $s_Prefix = "[_NetWebView2_ExportPageData]:" & " Format:" & $iFormat & " FilePath:" & (($sFilePath) ? ($sFilePath) : ('"EMPTY"'))
Local $oMyError = ObjEvent("AutoIt.Error", __NetWebView2_COMErrFunc) ; Local COM Error Handler
#forceref $oMyError
#TODO $sParameters - search for => "name": "captureSnapshot" ; https://github.com/ChromeDevTools/devtools-protocol/blob/master/json/browser_protocol.json
Local $s_Result = $oWebV2M.ExportPageData($iFormat, $sFilePath)
If StringLeft($s_Result, 6) = 'ERROR:' Then SetError(1)
__NetWebView2_Log(@ScriptLineNumber, $s_Prefix & " RESULT:" & ((@error) ? ($s_Result) : ("SUCCESS")), 1)
Return SetError(@error, @extended, $s_Result)
EndFunc ;==>_NetWebView2_ExportPageData
; #FUNCTION# ====================================================================================================================
; Name ..........: _NetWebView2_GetSource
; Description ...:
; Syntax ........: _NetWebView2_GetSource($oWebV2M)
; Parameters ....: $oWebV2M - an object.
; Return values .: None
; Author ........: mLipok
; Modified ......:
; Remarks .......:
; Related .......:
; Link ..........:
; Example .......: No
; ===============================================================================================================================
Func _NetWebView2_GetSource($oWebV2M)
Local Const $s_Prefix = "[_NetWebView2_GetSource]:"
Local $oMyError = ObjEvent("AutoIt.Error", __NetWebView2_COMErrFunc) ; Local COM Error Handler
#forceref $oMyError
Local $sSource = $oWebV2M.GetSource()
If @error Then __NetWebView2_Log(@ScriptLineNumber, $s_Prefix, 1)
Return SetError(@error, @extended, $sSource)
EndFunc ;==>_NetWebView2_GetSource
; #FUNCTION# ====================================================================================================================
; Name ..........: _NetWebView2_NavigateToPDF
; Description ...: Navigate to a PDF (local PDF file or online direct URL link to PDF file)
; Syntax ........: _NetWebView2_NavigateToPDF($oWebV2M, $s_URL_or_FilePath[, $s_Parameters = ''[, $iWaitMessage = $NETWEBVIEW2_MESSAGE__TITLE_CHANGED[,
; $sExpectedTitle = ""[, $iTimeOut_ms = 5000[, $iSleepAfter_ms = 1000[, $bFreeze = True]]]]]])
; Parameters ....: $oWebV2M - an object.
; $s_URL_or_FilePath - a string value.
; $s_Parameters - [optional] a string value. Default is ''.
; $iWaitMessage - [optional] an integer value. Default is $NETWEBVIEW2_MESSAGE__TITLE_CHANGED.
; $sExpectedTitle - [optional] Expected title to LoadWait for, as StringRegExp() pattern, By Default vaule it will compute the $s_URL_or_FilePath to guess RegExp for the Title
; $iTimeOut_ms - [optional] Maximum time to wait in milliseconds. 0 for infinite. Default is 5000ms
; $iSleepAfter_ms - [optional] an integer value. Default is 1000.
; $bFreeze - [optional] a boolean value. Default is True.
; Return values .: None
; Author ........: mLipok
; Modified ......:
; Remarks .......:
; Related .......:
; Link ..........:
; Example .......: No
; ===============================================================================================================================
Func _NetWebView2_NavigateToPDF($oWebV2M, $s_URL_or_FilePath, Const $s_Parameters = '', $iWaitMessage = $NETWEBVIEW2_MESSAGE__TITLE_CHANGED, $sExpectedTitle = Default, $iTimeOut_ms = 5000, Const $iSleepAfter_ms = 1000, Const $bFreeze = True)
Local Const $s_Prefix = "[_NetWebView2_NavigateToPDF]: URL_or_File:" & $s_URL_or_FilePath ; #TODO suplement
If (Not IsObj($oWebV2M)) Or ObjName($oWebV2M, $OBJ_PROGID) <> 'NetWebView2Lib.WebView2Manager' Then Return SetError(1, 0, "ERROR: Invalid Object")
If $sExpectedTitle = Default Then
Local $aFilePath = StringSplit($s_URL_or_FilePath, "\")
If @error Then
$sExpectedTitle = ''
Else
$sExpectedTitle = $aFilePath[$aFilePath[0]]
$sExpectedTitle = StringReplace($sExpectedTitle, '(', '\(')
$sExpectedTitle = StringReplace($sExpectedTitle, ')', '\)')
$sExpectedTitle = StringReplace($sExpectedTitle, '.', '\.')
EndIf
EndIf
If FileExists($s_URL_or_FilePath) Then
$s_URL_or_FilePath = StringReplace($s_URL_or_FilePath, '\', '/')
$s_URL_or_FilePath = StringReplace($s_URL_or_FilePath, ' ', '%20')
$s_URL_or_FilePath = "file:///" & $s_URL_or_FilePath
EndIf
If $s_Parameters Then
$s_URL_or_FilePath &= $s_Parameters
#TIP: FitToPage: https://stackoverflow.com/questions/78820187/how-to-change-webview2-fit-to-page-button-on-pdf-toolbar-default-to-fit-to-width#comment138971950_78821231
#TIP: Open desired PAGE: https://stackoverflow.com/questions/68500164/cycle-pdf-pages-in-wpf-webview2#comment135402565_68566860
EndIf
Local $idPic = 0
$oWebV2M.LockWebView()
If $bFreeze Then __NetWebView2_freezer($oWebV2M, $idPic)
_NetWebView2_Navigate($oWebV2M, $s_URL_or_FilePath, $iWaitMessage, $sExpectedTitle, $iTimeOut_ms)
If Not @error Then __NetWebView2_Sleep($iSleepAfter_ms)
If @error Then Return SetError(@error, @extended, '')
__NetWebView2_Log(@ScriptLineNumber, $s_Prefix, 1)
If $bFreeze And $idPic Then __NetWebView2_freezer($oWebV2M, $idPic)
$oWebV2M.UnLockWebView()
EndFunc ;==>_NetWebView2_NavigateToPDF
; #FUNCTION# ====================================================================================================================
; Name ..........: _NetWebView2_PrintToPdfStream
; Description ...: Print web content to PDF
; Syntax ........: _NetWebView2_PrintToPdfStream($oWebV2M, $b_TBinary_FBase64)
; Parameters ....: $oWebV2M - an object.
; $b_TBinary_FBase64 - a boolean value.
; Return values .: Success - binary or string with Base64 encoded binary content of the PDF
; Failure - string with error description "ERROR: ........." and set @error to 1
; Author ........: mLipok, ioa747
; Modified ......:
; Remarks .......:
; Related .......:
; Link ..........:
; Example .......: No
; ===============================================================================================================================
Func _NetWebView2_PrintToPdfStream($oWebV2M, $b_TBinary_FBase64)
Local Const $s_Prefix = "[_NetWebView2_PrintToPdfStream]: TBinary_FBase64:" & $b_TBinary_FBase64
Local $oMyError = ObjEvent("AutoIt.Error", __NetWebView2_COMErrFunc) ; Local COM Error Handler
#forceref $oMyError
Local $s_Result = $oWebV2M.PrintToPdfStream()
__NetWebView2_Log(@ScriptLineNumber, $s_Prefix, 1)
If StringInStr($s_Result, 'ERROR:') Then SetError(1)
If $b_TBinary_FBase64 Then
; decode Base64 encoded data do Binary
$s_Result = _NetWebView2_DecodeB64ToBinary($oWebV2M, $s_Result)
EndIf
__NetWebView2_Log(@ScriptLineNumber, $s_Prefix & " RESULT:" & ((@error) ? ($s_Result) : ("SUCCESS")), 1)
Return SetError(@error, @extended, $s_Result)
EndFunc ;==>_NetWebView2_PrintToPdfStream
#EndRegion ; === NetWebView2Lib UDF === _NetWebView2_* helper functions
#Region ; === NetWebView2Lib UDF === New Core Method Wrappers
; #FUNCTION# ====================================================================================================================
; Name...........: _NetWebView2_AddInitializationScript
; Description ...: Adds a JavaScript to be executed before any other script when a new page is loaded.
; Syntax.........: _NetWebView2_AddInitializationScript($oWeb, $sScript)
; Parameters ....: $oWeb - The NetWebView2 Manager object.
; $vScript - The JavaScript code to inject (String) OR the full path to a JavaScript file.
; Return values .: Success - Returns a Script ID (string).
; Failure - Returns the error message and sets @error.
; Author ........: ioa747, mLipok
; Modified ......:
; Remarks .......:
; Related .......: _NetWebView2_RemoveInitializationScript
; Link ..........:
; Example .......: No
; ===============================================================================================================================
Func _NetWebView2_AddInitializationScript($oWebV2M, $vScript)
If (Not IsObj($oWebV2M)) Or ObjName($oWebV2M, $OBJ_PROGID) <> 'NetWebView2Lib.WebView2Manager' Then Return SetError(1, 0, "ERROR: Invalid Object")
; Smart Detection
If FileExists($vScript) Then $vScript = FileRead($vScript)
Local $sScriptId = $oWebV2M.AddInitializationScript($vScript)
If StringInStr($sScriptId, "ERROR:") Then Return SetError(2, 0, $sScriptId)
Return SetError(0, 0, $sScriptId)
EndFunc ;==>_NetWebView2_AddInitializationScript
; #FUNCTION# ====================================================================================================================
; Name...........: _NetWebView2_RemoveInitializationScript
; Description....: Removes a previously added initialization script using its ID.
; Syntax.........: _NetWebView2_RemoveInitializationScript($oWebV2M, $sScriptId)
; Parameters.....: $oWebV2M - The Net WebView2 instance to manipulate.
; $sScriptId - The ID of the initialization script to remove.
; Return values .: Success - True
; Failure - False and sets @error
; Author ........: ioa747, mLipok
; Modified ......:
; Remarks .......:
; Related .......: _NetWebView2_AddInitializationScript
; Link ..........:
; Example .......: No
; ===============================================================================================================================
Func _NetWebView2_RemoveInitializationScript($oWebV2M, $sScriptId)
If (Not IsObj($oWebV2M)) Or ObjName($oWebV2M, $OBJ_PROGID) <> 'NetWebView2Lib.WebView2Manager' Then Return SetError(1, 0, False) ; Error 1: Not an object
$oWebV2M.RemoveInitializationScript($sScriptId)
Return SetError(@error, 0, (@error ? False : True))
EndFunc ;==>_NetWebView2_RemoveInitializationScript
; #FUNCTION# ====================================================================================================================
; Name...........: _NetWebView2_SetVirtualHostNameToFolderMapping
; Description ...: Maps a custom host name to a local folder path (bypasses CORS).
; Syntax.........: _NetWebView2_SetVirtualHostNameToFolderMapping($oWebV2M, $sHostName, $sFolderPath[, $iAccessKind = 0])
; Parameters ....: $oWebV2M - The NetWebView2 Manager object.
; $sHostName - The virtual domain (e.g., "myapp.local").
; $sFolderPath - The absolute path to the local folder.
; $iAccessKind - 0: Allow, 1: Deny, 2: Allow (Cross-Origin restricted).
; Return values .: Success - True
; Failure - False and sets @error
; Author ........: ioa747, mLipok
; Modified ......:
; Remarks .......:
; Related .......:
; Link ..........:
; Example .......: No
; ===============================================================================================================================
Func _NetWebView2_SetVirtualHostNameToFolderMapping($oWebV2M, $sHostName, $sFolderPath, $iAccessKind = 0)
If (Not IsObj($oWebV2M)) Or ObjName($oWebV2M, $OBJ_PROGID) <> 'NetWebView2Lib.WebView2Manager' Then Return SetError(1, 0, False)
$oWebV2M.SetVirtualHostNameToFolderMapping($sHostName, $sFolderPath, $iAccessKind)
Return SetError(@error, 0, (@error ? False : True))
EndFunc ;==>_NetWebView2_SetVirtualHostNameToFolderMapping
; #FUNCTION# ====================================================================================================================
; Name...........: _NetWebView2_SetLockState
; Description ...: Locks or unlocks the manager to prevent COM calls during critical operations (e.g., Cleanup).
; Syntax.........: _NetWebView2_SetLockState($oWebV2M, $bLockState)
; Parameters ....: $oWebV2M - The NetWebView2 Manager object.
; $bLockState - True to lock (prevent calls), False to unlock.
; Return values .: Success - True
; Failure - False and sets @error
; Author ........: ioa747, mLipok
; Modified ......:
; Remarks .......:
; Related .......:
; Link ..........:
; Example .......: No
; ===============================================================================================================================
Func _NetWebView2_SetLockState($oWebV2M, $bLockState)
If (Not IsObj($oWebV2M)) Or ObjName($oWebV2M, $OBJ_PROGID) <> 'NetWebView2Lib.WebView2Manager' Then Return SetError(1, 0, False)
$oWebV2M.SetLockState($bLockState)
Return SetError(@error, 0, (@error ? False : True))
EndFunc ;==>_NetWebView2_SetLockState
; #FUNCTION# ====================================================================================================================
; Name...........: _NetWebView2_EncodeBinaryToB64
; Description ...: High-performance binary to Base64 string encoding using the C# Core.
; Syntax.........: _NetWebView2_EncodeBinaryToB64($oWebV2M, ByRef $dBinary)
; Parameters ....: $oWebV2M - The NetWebView2 Manager object.
; $dBinary - The binary data to encode.
; Return values .: Success - Returns a Base64 encoded string.
; Failure - Returns an empty string and sets @error.
; Author ........: ioa747, mLipok
; Modified ......:
; Remarks .......:
; Related .......: _NetWebView2_DecodeB64ToBinary
; Link ..........:
; Example .......: No
; ===============================================================================================================================
Func _NetWebView2_EncodeBinaryToB64($oWebV2M, ByRef $dBinary)
If (Not IsObj($oWebV2M)) Or ObjName($oWebV2M, $OBJ_PROGID) <> 'NetWebView2Lib.WebView2Manager' Then Return SetError(1, 0, "")
Local $sResult = $oWebV2M.EncodeBinaryToB64($dBinary)
If @error Then Return SetError(@error, 0, "")
Return SetError(0, 0, $sResult)
EndFunc ;==>_NetWebView2_EncodeBinaryToB64
; #FUNCTION# ====================================================================================================================
; Name...........: _NetWebView2_DecodeB64ToBinary
; Description ...: High-performance Base64 string to binary data decoding using the C# Core.
; Syntax.........: _NetWebView2_DecodeB64ToBinary($oWebV2M, ByRef $sB64)
; Parameters ....: $oWebV2M - The NetWebView2 Manager object.
; $sB64 - The Base64 encoded string to decode.
; Return values .: Success - Returns binary data.
; Failure - Returns empty binary and sets @error.
; Author ........: ioa747, mLipok
; Modified ......:
; Remarks .......:
; Related .......: _NetWebView2_EncodeBinaryToB64
; Link ..........:
; Example .......: No
; ===============================================================================================================================
Func _NetWebView2_DecodeB64ToBinary($oWebV2M, ByRef $sB64)
If (Not IsObj($oWebV2M)) Or ObjName($oWebV2M, $OBJ_PROGID) <> 'NetWebView2Lib.WebView2Manager' Then Return SetError(1, 0, Binary(""))
Local $dResult = $oWebV2M.DecodeB64ToBinary($sB64)
If @error Then Return SetError(@error, 0, Binary(""))
Return SetError(0, 0, $dResult)
EndFunc ;==>_NetWebView2_DecodeB64ToBinary
; #FUNCTION# ====================================================================================================================
; Name...........: _NetWebView2_SetBuiltInErrorPageEnabled
; Description ...: Enables or disables the built-in WebView2 error pages (e.g., "No Internet").
; Syntax.........: _NetWebView2_SetBuiltInErrorPageEnabled($oWeb, $bEnabled)
; Parameters ....: $oWeb - The NetWebView2 Manager object.
; $bEnabled - True to show default error pages, False to hide them.
; Return values .: Success - True
; Failure - False and sets @error
; Author ........: ioa747, mLipok
; Modified ......:
; Remarks .......:
; Related .......: _NetWebView2_EncodeBinaryToB64
; Link ..........:
; Example .......: No
; ===============================================================================================================================
Func _NetWebView2_SetBuiltInErrorPageEnabled($oWebV2M, $bEnabled)
If (Not IsObj($oWebV2M)) Or ObjName($oWebV2M, $OBJ_PROGID) <> 'NetWebView2Lib.WebView2Manager' Then Return SetError(1, 0, False)
$oWebV2M.IsBuiltInErrorPageEnabled = $bEnabled
Return SetError(@error, 0, (@error ? False : True))
EndFunc ;==>_NetWebView2_SetBuiltInErrorPageEnabled
; #FUNCTION# ====================================================================================================================
; Name...........: _WebView2_FrameGetHtmlSource
; Description....: Synchronously retrieves the full HTML source of a frame.
; Syntax.........: _WebView2_FrameGetHtmlSource($oFrame)
; Parameters.....: $oFrame - The WebView2Frame object.
; Return values..: Success - Clean HTML string.
; Failure - Sets @error and returns empty string.
; Author ........: ioa747
; Modified ......:
; Remarks .......:
; Related .......:
; Link ..........:
; Example .......: No
; ===============================================================================================================================
Func _WebView2_FrameGetHtmlSource($oFrame)
If Not IsObj($oFrame) Then Return SetError(1, 0, "")
; Execute script synchronously
Local $sRaw = $oFrame.ExecuteScriptWithResult("document.documentElement.outerHTML")
; Basic validation
If $sRaw = "null" Or $sRaw = "" Then Return ""
If StringLeft($sRaw, 6) = "ERROR:" Then Return SetError(2, 0, "")