Results 1 to 21 of 21

Thread: [VB6] cWebView2 — RC6-compatible WebView2 wrapper

  1. #1

    Thread Starter
    PowerPoster wqweto's Avatar
    Join Date
    May 2011
    Location
    Sofia, Bulgaria
    Posts
    6,200

    [VB6] cWebView2 — RC6-compatible WebView2 wrapper

    This is a drop-in replacement of vbRichClient6's cWebView2 class, implemented in pure VB6 directly against the official Microsoft WebView2 COM API.

    No RC6.dll dependency, no dependency on the WebView2 SDK typelib — the only redistributable is WebView2Loader.dll authored by Microsoft deployed next to your exe, targeting the Evergreen WebView2 Runtime installed on the client machine.

    Additions beyond RC6 parity

    Methods with no RC6 counterpart, exposed because the native plumbing is cheap and the features are frequently requested:

    • PrintToPdf(ResultFilePath, [SecondsToWaitForPrintComplete], [Landscape], [ScaleFactor], [PageWidth/PageHeight], [margins], [ShouldPrintBackgrounds], [ShouldPrintSelectionOnly], [ShouldPrintHeaderAndFooter], [HeaderTitle], [FooterUri]) - blocking (or fire-and-forget at 0 seconds), returns True/False, Empty on timeout.
    • AddBrowserExtension(ExtensionFolderPath) - installs an unpacked extension into the profile, returns the extension Id (empty string on failure). Requires BindTo's AreBrowserExtensionsEnabled:=True optional parameter - must be decided before environment creation, and all instances sharing a user data folder must agree on it.
    • GetBrowserExtensions() - returns a Collection of per-extension Collections (Id, Name, IsEnabled keys), keyed by extension Id. Extension APIs need a recent Evergreen runtime; on older runtimes these return empty results.
    • SetVirtualHostNameToFolderMapping(HostName, FolderPath, [AccessKind]) / ClearVirtualHostNameToFolderMapping(HostName) - serve a local folder as https://<HostName>/... AccessKind defaults to HostResourceAccess_DENY (the mapped origin still serves its own content; other origins can't read it - Microsoft's recommended default). Mappings persist for the browser instance's lifetime: set once after BindTo, then navigate. The host name must be a bare name - no scheme or slashes.
    • Stop_ - cancels in-flight navigation/loading, WebBrowser.Stop style (trailing underscore because Stop is a VB6 keyword).
    • PostWebMessageAsString/PostWebMessageAsJson - host-to-page messaging; page script receives via chrome.webview.addEventListener('message', ...).
    • ContainsFullScreenElement - detect HTML fullscreen (resize/borderless the host form).
    • IsBuiltInErrorPageEnabled - the one base setting RC6 didn't surface.
    • IsMuted (get/let), IsDocumentPlayingAudio - tab audio control.
    • Default download dialog control - OpenDefaultDownloadDialog/CloseDefaultDownloadDialog/IsDefaultDownloadDialogOpen, DefaultDownloadDialogCornerAlignment and DefaultDownloadDialogMargin.
    • Profile properties - PreferredColorScheme (dark mode), DefaultDownloadFolderPath, PreferredTrackingPreventionLevel, ProfileName, ProfilePath, IsInPrivateModeEnabled.
    • StatusBarText, BrowserVersion - runtime/status introspection; OpenTaskManagerWindow - browser diagnostics.
    • CallDevToolsProtocolMethodForSession - CDP against a specific target session, same blocking semantics as CallDevToolsProtocolMethod.
    • SetBoundsAndZoomFactor, NotifyParentWindowPositionChanged (also called internally on resize/move), HosthWnd is now writable (re-hosting).
    • TrySuspend/ResumeFromSuspend/IsSuspended - release memory while in the background; TrySuspend hides the webview first (a native precondition), ResumeFromSuspend makes it visible again.
    • ClearBrowsingData(DataKinds), ClearBrowsingDataInTimeRange(DataKinds, StartTime, EndTime), ClearBrowsingDataAll - clear cache/cookies/history etc per eWebView2BrowsingDataKinds flags; blocking with the usual fire-and-forget at 0 seconds.
    • Cookie management - GetCookies([URI]) returns a Collection of per-cookie Collections (Name, Value, Domain, Path, IsSession, Expires, IsSecure, IsHttpOnly, SameSite keys); AddOrUpdateCookie(Name, Value, Domain, [Path], [Expires], ...) (zero Expires = session cookie); DeleteCookies(Name, URI) (both required - cookies are matched by name and URI natively); DeleteAllCookies.
    • PrintToPdfStream([settings...]) - same settings as PrintToPdf but returns the PDF as a Byte() array, no file involved. ShowPrintUI opens the browser or system print dialog.


    A handful of native WebView2/WebBrowser-style events with no RC6 counterpart are also exposed, since the native plumbing is either free (already needed for something else) or fills a gap the JS-bridge-based events can't:

    • ContentLoading(IsErrorPage) - fires before NavigationCompleted, akin to WebBrowser's early loading moment.
    • HistoryChanged() - back/forward stack changed; pair with CanGoBack/CanGoForward.
    • WindowCloseRequested() - page called window.close().
    • ZoomFactorChanged() - native counterpart to the ZoomFactor property.
    • MoveFocusRequested(Reason, Handled) - Tab/Shift+Tab reached the edge of the web content; Reason reuses eWebView2FocusReason.
    • DOMContentLoaded() - the classic DOM-ready moment, between ContentLoading and DocumentComplete.
    • StatusBarTextChanged(Text) - hover-link/status text, pairs with the StatusBarText property.
    • ContainsFullScreenElementChanged() - page entered/left HTML fullscreen; read ContainsFullScreenElement to react.
    • BasicAuthenticationRequested(URI, Challenge, UserName, Password, Cancel) - supply credentials for HTTP basic/proxy auth via the ByRef params. Note Chromium's flow: the challenged navigation first completes with WebErrorStatus 17 (VALID_AUTHENTICATION_CREDENTIALS_REQUIRED), then the authenticated retry loads.
    • ContextMenuRequested(PageURI, LinkURI, SelectionText, ScreenX, ScreenY, Handled) - the native context-menu event, richer than the JS-injected UserContextMenu (which only reports coordinates): carries link/selection info and can actually suppress the browser's context menu via Handled. Deliberately simplified - no custom menu item injection/CustomItemSelected. UserContextMenu is unchanged and still fires alongside it.

    cheers,
    </wqw>

  2. #2
    Addicted Member
    Join Date
    Oct 2014
    Posts
    133

    Re: [VB6] cWebView2 — RC6-compatible WebView2 wrapper

    Quote Originally Posted by wqweto View Post
    This is a drop-in replacement of vbRichClient6's cWebView2 class, implemented in pure VB6 directly against the official Microsoft WebView2 COM API.

    No RC6.dll dependency, no dependency on the WebView2 SDK typelib — the only redistributable is WebView2Loader.dll authored by Microsoft deployed next to your exe, targeting the Evergreen WebView2 Runtime installed on the client machine.

    cheers,
    </wqw>
    wqweto, hello! Great job! The cWebView2 features you provided are really powerful and have been a huge help to me. Thank you so much!

  3. #3
    Addicted Member saturnian's Avatar
    Join Date
    Dec 2017
    Location
    France
    Posts
    145

    Re: [VB6] cWebView2 — RC6-compatible WebView2 wrapper

    Fantastic job! I'm going to test this right away!

  4. #4

  5. #5
    Addicted Member saturnian's Avatar
    Join Date
    Dec 2017
    Location
    France
    Posts
    145

    Re: [VB6] cWebView2 — RC6-compatible WebView2 wrapper

    I dreamed of it, and you made it happen! Thank you!!

    Do you think it would be possible to add some features currently available in the latest versions of WebView2?

    For example:


    Thanks for your reply!
    François

  6. #6

    Thread Starter
    PowerPoster wqweto's Avatar
    Join Date
    May 2011
    Location
    Sofia, Bulgaria
    Posts
    6,200

    Re: [VB6] cWebView2 — RC6-compatible WebView2 wrapper

    Claude just released version 1.0.1

    What's new

    • PrintToPdf method — saves the current page to PDF with optional orientation, scale, page size, margins and header/footer settings
    • Browser extension management — AddBrowserExtension/GetBrowserExtensions methods and new AreBrowserExtensionsEnabled optional parameter of BindTo
    • SecondsToWaitForXxx=0 and jsCallTimeOutSeconds=0 now mean fire-and-forget (execute async, return success immediately)
    • Deterministic teardown on Shutdown (controller Close), re-binding after Shutdown supported, missing loader reported immediately instead of as timeout

    cheers,
    </wqw>

  7. #7
    Addicted Member saturnian's Avatar
    Join Date
    Dec 2017
    Location
    France
    Posts
    145

    Re: [VB6] cWebView2 — RC6-compatible WebView2 wrapper

    Quote Originally Posted by wqweto View Post
    Claude just released version 1.0.1

    What's new

    • PrintToPdf method — saves the current page to PDF with optional orientation, scale, page size, margins and header/footer settings
    • Browser extension management — AddBrowserExtension/GetBrowserExtensions methods and new AreBrowserExtensionsEnabled optional parameter of BindTo
    • SecondsToWaitForXxx=0 and jsCallTimeOutSeconds=0 now mean fire-and-forget (execute async, return success immediately)
    • Deterministic teardown on Shutdown (controller Close), re-binding after Shutdown supported, missing loader reported immediately instead of as timeout

    cheers,
    </wqw>
    Wow... I'm speechless, stunned, dumbfounded!
    It couldn't be faster!
    You're the best! Thank you!

  8. #8
    Fanatic Member
    Join Date
    Jun 2016
    Location
    España
    Posts
    635

    Re: [VB6] cWebView2 — RC6-compatible WebView2 wrapper

    very good work.
    I'm having trouble adding extensions.

    SOLVED
    Thanks
    Last edited by yokesee; Jul 9th, 2026 at 12:52 PM.

  9. #9
    Addicted Member saturnian's Avatar
    Join Date
    Dec 2017
    Location
    France
    Posts
    145

    Re: [VB6] cWebView2 — RC6-compatible WebView2 wrapper

    Um... ..., I hardly dare ask...

    Can Claude.wqweto.ai do anything about SetVirtualHostNameToFolderMapping ? ? ?

    ...I'm going to hide and pray in my cave...

    François

  10. #10

  11. #11

    Thread Starter
    PowerPoster wqweto's Avatar
    Join Date
    May 2011
    Location
    Sofia, Bulgaria
    Posts
    6,200

    Re: [VB6] cWebView2 — RC6-compatible WebView2 wrapper

    Download: VbWebView2 1.0.3

    What's new

    • Cookie management — GetCookies, AddOrUpdateCookie, DeleteCookies, DeleteAllCookies
    • BasicAuthenticationRequested event — supply credentials for HTTP basic/proxy auth
    • PrintToPdfStream method — current page as PDF in a Byte() array, no file involved; ShowPrintUI opens the print dialog
    • TrySuspend/ResumeFromSuspend/IsSuspended — release memory while in the background
    • ClearBrowsingData/ClearBrowsingDataInTimeRange/ClearBrowsingDataAll — clear cache/cookies/history per eWebView2BrowsingDataKinds flags
    • New events — DOMContentLoaded, StatusBarTextChanged, ContainsFullScreenElementChanged
    • Profile properties — PreferredColorScheme (dark mode), DefaultDownloadFolderPath, PreferredTrackingPreventionLevel, ProfileName, ProfilePath, IsInPrivateModeEnabled
    • Host-to-page messaging — PostWebMessageAsString/PostWebMessageAsJson
    • Assorted — Stop_, IsMuted/IsDocumentPlayingAudio, default download dialog control, ContainsFullScreenElement, IsBuiltInErrorPageEnabled, StatusBarText, BrowserVersion, OpenTaskManagerWindow, CallDevToolsProtocolMethodForSession, SetBoundsAndZoomFactor, NotifyParentWindowPositionChanged, writable HosthWnd
    • GetMostRecentInstallPath now fills VersionString with the resolved runtime version instead of raising "not yet implemented"

    cheers,
    </wqw>

  12. #12
    Addicted Member saturnian's Avatar
    Join Date
    Dec 2017
    Location
    France
    Posts
    145

    Re: [VB6] cWebView2 — RC6-compatible WebView2 wrapper

    Quote Originally Posted by wqweto View Post
    Download: VbWebView2 1.0.3

    What's new

    • Cookie management — GetCookies, AddOrUpdateCookie, DeleteCookies, DeleteAllCookies
    • BasicAuthenticationRequested event — supply credentials for HTTP basic/proxy auth
    • PrintToPdfStream method — current page as PDF in a Byte() array, no file involved; ShowPrintUI opens the print dialog
    • TrySuspend/ResumeFromSuspend/IsSuspended — release memory while in the background
    • ClearBrowsingData/ClearBrowsingDataInTimeRange/ClearBrowsingDataAll — clear cache/cookies/history per eWebView2BrowsingDataKinds flags
    • New events — DOMContentLoaded, StatusBarTextChanged, ContainsFullScreenElementChanged
    • Profile properties — PreferredColorScheme (dark mode), DefaultDownloadFolderPath, PreferredTrackingPreventionLevel, ProfileName, ProfilePath, IsInPrivateModeEnabled
    • Host-to-page messaging — PostWebMessageAsString/PostWebMessageAsJson
    • Assorted — Stop_, IsMuted/IsDocumentPlayingAudio, default download dialog control, ContainsFullScreenElement, IsBuiltInErrorPageEnabled, StatusBarText, BrowserVersion, OpenTaskManagerWindow, CallDevToolsProtocolMethodForSession, SetBoundsAndZoomFactor, NotifyParentWindowPositionChanged, writable HosthWnd
    • GetMostRecentInstallPath now fills VersionString with the resolved runtime version instead of raising "not yet implemented"

    cheers,
    </wqw>
    incredible ! It's a dream !

  13. #13
    Addicted Member saturnian's Avatar
    Join Date
    Dec 2017
    Location
    France
    Posts
    145

    Re: [VB6] cWebView2 — RC6-compatible WebView2 wrapper

    I just found a small difference between your code and the RC6.

    The RC6's BindTo function returns 1 when everything went well and 0 otherwise.

    Your code returns 0 when everything went well and an error code otherwise.

    For complete compatibility, I made this small modification to the BindTo function.

    Code:
    .....
        Set oHandler = New cWebView2Callback
        oHandler.Init Me
        hResult = pvCreateWebView2Environment(browserInstallPath, userDataFolder, oOptions, oHandler)
        If hResult <> 0 Then
            BindTo = 0 ' hResult
            Exit Function
        End If
        If Not pvPumpUntil(m_bInitComplete, SecondsToWaitForInitComplete) Then
            BindTo = 0 ' RPC_E_TIMEOUT
            Exit Function
        End If
        BindTo = IIf(m_hInitError = 0, 1, 0) ' m_hInitError
        Exit Function
    EH:
        BindTo = 0 ' Err.Number
        PrintError "BindTo"
    End Function
    Last edited by saturnian; Yesterday at 09:19 AM.

  14. #14
    Addicted Member saturnian's Avatar
    Join Date
    Dec 2017
    Location
    France
    Posts
    145

    Re: [VB6] cWebView2 — RC6-compatible WebView2 wrapper

    Hello wqweto

    I'm having a real problem with JavaScript execution latency when using the cWebview2 classes in my source code.


    If I take the demo code provided in the GitHub repository, add a command button, and paste the code below, I experience an abnormally long latency before receiving the response in JSmessage.

    This happens with every JavaScript call.
    Do you have any explanation?


    Code:
    Private Sub cmdCommand1_Click()
        ' Some javascript code.... to manipulate the document currently displayed
        '*************************************************************************
        ' allows you to programmatically click on an element of the page
        m_oWebView2.AddScriptToExecuteOnDocumentCreated "function ElementClick(myElement){ window.document.getElementById(myElement).click(); }"
        ' allows you to retrieve the value displayed in an element of the page. to call the function use the following code : OrdoWebView1.RunJs ("getQSValue", "txt1")
        m_oWebView2.AddScriptToExecuteOnDocumentCreated "function getQSValue(qsExpr){return document.getElementById((qsExpr)).value}" ' You can also use : OrdoWebView1.AddScriptToExecuteOnDocumentCreated "function getQSValue(qsExpr){return document.querySelector(qsExpr).value}"
        ' allows you to set the value displayed in an element of the page. to call the function use the following code : OrdoWebView1.RunJs ("setQSValue", "txt1", "NewValue")
        m_oWebView2.AddScriptToExecuteOnDocumentCreated "function setQSValue(qsExpr,strValue){document.getElementById((qsExpr)).value=strValue}"
        m_oWebView2.AddScriptToExecuteOnDocumentCreated "function btn1_click(){ vbH().RaiseMessageEvent('btn1_click','') }"
        m_oWebView2.AddScriptToExecuteOnDocumentCreated _ 
           "document.addEventListener(""submit"", function() {" & _
            " var message_alert = """";" & _
            " var elems = document.forms[0].elements;" & _
            " for (var i = 0; i < elems.length; i++) {" & _
            "   if (elems[i].value !== """") {" & _
            "     message_alert += i + "" : "" + elems[i].name + "" : "" + elems[i].value + "" : "" + elems[i].type + ""\n"";" & _
            "   }" & _
            " }" & _
            " vbH().RaiseMessageEvent('Submit', message_alert);" & _
            "}, false);"
        OrdoWebView1.NavigateToString "<!DOCTYPE html><html><head><title>OrdoWebview2 Javascript Test</title></head>" & _
                              "<body style=""color:#808000"">" & _
                              "<br><div>Get the TextBox value using Javascript...</div><br>" & _
                              "<form id='form1' onsubmit='return false;'>" & _
                              "<input id='txt1' name='txt1' value='Hello World'>" & _
                              "<button id='btn1' type='button' onclick='btn1_click()'>Get</button>" & _
                              "</form>" & _
                              "</body></html>"
    End Sub
    
    Private Sub m_oWebView2_JSMessage(ByVal sMsg As String, ByVal sMsgContent As String, oJSONContent As Collection)
        If sMsg = "btn1_click" Then
            MsgBox "Textbox 'txt1' value is: " & m_oWebView2.jsRun("getQSValue", "txt1")
        ElseIf sMsg = "title_change" Then
            Caption = "cWebView2 Test Harness - " & sMsgContent
        ElseIf Not oJSONContent Is Nothing Then
            lblStatus.Caption = lblStatus.Caption & " | json.answer=" & oJSONContent("answer")
        ElseIf LenB(sMsgContent) <> 0 Then
            lblStatus.Caption = lblStatus.Caption & " | " & sMsg & "=" & sMsgContent
        Else
            lblStatus.Caption = lblStatus.Caption & " | msg=" & sMsg
        End If
    
    
    End Sub
    Note: I've tested this on several machines running Windows 10 and 11 with the same result.


    Last edit :
    Apparently, the jsRun function is causing the problem.
    I'll continue investigating.
    Last edited by saturnian; Yesterday at 01:07 PM.

  15. #15
    Addicted Member saturnian's Avatar
    Join Date
    Dec 2017
    Location
    France
    Posts
    145

    Re: [VB6] cWebView2 — RC6-compatible WebView2 wrapper

    I found it!
    jsRun cannot be called in the JSMessage event!
    Just add a timer and it works!
    Weird!

  16. #16
    PowerPoster VanGoghGaming's Avatar
    Join Date
    Jan 2020
    Location
    Eve Online - Mining, Missions & Market Trading!
    Posts
    2,649

    Talking Re: [VB6] cWebView2 — RC6-compatible WebView2 wrapper

    Quote Originally Posted by saturnian View Post
    Hello wqweto

    I'm having a real problem with JavaScript execution latency when using the cWebview2 classes in my source code.


    If I take the demo code provided in the GitHub repository, add a command button, and paste the code below, I experience an abnormally long latency before receiving the response in JSmessage.

    This happens with every JavaScript call.
    Do you have any explanation?


    Code:
    Private Sub cmdCommand1_Click()
        ' Some javascript code.... to manipulate the document currently displayed
        '*************************************************************************
        ' allows you to programmatically click on an element of the page
        m_oWebView2.AddScriptToExecuteOnDocumentCreated "function ElementClick(myElement){ window.document.getElementById(myElement).click(); }"
        ' allows you to retrieve the value displayed in an element of the page. to call the function use the following code : OrdoWebView1.RunJs ("getQSValue", "txt1")
        m_oWebView2.AddScriptToExecuteOnDocumentCreated "function getQSValue(qsExpr){return document.getElementById((qsExpr)).value}" ' You can also use : OrdoWebView1.AddScriptToExecuteOnDocumentCreated "function getQSValue(qsExpr){return document.querySelector(qsExpr).value}"
        ' allows you to set the value displayed in an element of the page. to call the function use the following code : OrdoWebView1.RunJs ("setQSValue", "txt1", "NewValue")
        m_oWebView2.AddScriptToExecuteOnDocumentCreated "function setQSValue(qsExpr,strValue){document.getElementById((qsExpr)).value=strValue}"
        m_oWebView2.AddScriptToExecuteOnDocumentCreated "function btn1_click(){ vbH().RaiseMessageEvent('btn1_click','') }"
        m_oWebView2.AddScriptToExecuteOnDocumentCreated _ 
           "document.addEventListener(""submit"", function() {" & _
            " var message_alert = """";" & _
            " var elems = document.forms[0].elements;" & _
            " for (var i = 0; i < elems.length; i++) {" & _
            "   if (elems[i].value !== """") {" & _
            "     message_alert += i + "" : "" + elems[i].name + "" : "" + elems[i].value + "" : "" + elems[i].type + ""\n"";" & _
            "   }" & _
            " }" & _
            " vbH().RaiseMessageEvent('Submit', message_alert);" & _
            "}, false);"
        OrdoWebView1.NavigateToString "<!DOCTYPE html><html><head><title>OrdoWebview2 Javascript Test</title></head>" & _
                              "<body style=""color:#808000"">" & _
                              "<br><div>Get the TextBox value using Javascript...</div><br>" & _
                              "<form id='form1' onsubmit='return false;'>" & _
                              "<input id='txt1' name='txt1' value='Hello World'>" & _
                              "<button id='btn1' type='button' onclick='btn1_click()'>Get</button>" & _
                              "</form>" & _
                              "</body></html>"
    End Sub
    
    Private Sub m_oWebView2_JSMessage(ByVal sMsg As String, ByVal sMsgContent As String, oJSONContent As Collection)
        If sMsg = "btn1_click" Then
            MsgBox "Textbox 'txt1' value is: " & m_oWebView2.jsRun("getQSValue", "txt1")
        ElseIf sMsg = "title_change" Then
            Caption = "cWebView2 Test Harness - " & sMsgContent
        ElseIf Not oJSONContent Is Nothing Then
            lblStatus.Caption = lblStatus.Caption & " | json.answer=" & oJSONContent("answer")
        ElseIf LenB(sMsgContent) <> 0 Then
            lblStatus.Caption = lblStatus.Caption & " | " & sMsg & "=" & sMsgContent
        Else
            lblStatus.Caption = lblStatus.Caption & " | msg=" & sMsg
        End If
    
    
    End Sub
    Note: I've tested this on several machines running Windows 10 and 11 with the same result.


    Last edit :
    Apparently, the jsRun function is causing the problem.
    I'll continue investigating.


    I wanted to test your JavaScript code with the WinRT WebView interop class which allows you to host a WebView inside any hWnd without much ceremony. This demo project creates the WebView inside a PictureBox and loads your HTML code and the JavaScript functions.

    The WebView is created in Form_Load and once the async operation is completed it subscribes to the ScriptNotify event and executes the WebViewControl.NavigateToString method. When you click the Get button on your form, a MsgBox displays your message_alert string in the ScriptNotify event:

    Name:  WebView.png
Views: 37
Size:  13.0 KB

    frmWebView
    Code:
    Option Explicit
    
    Implements IAsyncOperationCompletedHandlerIWebViewControl
    Implements ITypedEventHandlerWebViewControlScriptNotify
    
    Private WebViewControlProcess As IWebViewControlProcess, WebViewControl As IWebViewControl, Params As IVector_HSTRING
    
    Private Sub Form_Load()
    Dim Rect As RECTF, RemoteLauncherOptions As IRemoteLauncherOptions
        Set RemoteLauncherOptions = NewObject("RemoteLauncherOptions"): Set Params = RemoteLauncherOptions.PreferredAppIds
        With picWebView
            Rect.Width = .ScaleX(.ScaleWidth, .ScaleMode, vbPixels): Rect.Height = .ScaleY(.ScaleHeight, .ScaleMode, vbPixels)
            Set WebViewControlProcess = NewObject("WebViewControlProcess")
            Set WebViewControlProcess.CreateWebViewControlAsync(.hWnd, 0&, Rect.X, Rect.Y, Rect.Width, Rect.Height).Completed = Me
        End With
    End Sub
    
    Private Sub IAsyncOperationCompletedHandlerIWebViewControl_Invoke(ByVal AsyncOperation As IAsyncOperationIWebViewControl, ByVal AsyncStatus As AsyncStatus)
    Dim AsyncInfo As IAsyncInfo
        Select Case AsyncStatus
            Case AsyncStatus_Completed
                Set WebViewControl = AsyncOperation.GetResults: WebViewControl.AddScriptNotify Me
                
                WebViewControl.NavigateToString StrRef("<!DOCTYPE html><html><head><title>WebView Javascript Test</title></head>" & _
                    "<script type='text/javascript'>" & _
                    "function getQSValue(qsExpr){return document.getElementById((qsExpr)).value;}" & _
                    "function setQSValue(qsExpr, strValue){document.getElementById((qsExpr)).value=strValue;}" & _
                    "document.addEventListener('submit', (e) => {" & _
                    "   var message_alert = '';" & _
                    "   var elems = e.target.elements;" & _
                    "       for (var i = 0; i < elems.length; i++) {" & _
                    "           if (elems[i].value !== '') {" & _
                    "               message_alert += i + ' : ' + elems[i].name + ' : ' + elems[i].value + ' : ' + elems[i].type + '\n';" & _
                    "           }" & _
                    "       }" & _
                    "   window.external.notify(message_alert);" & _
                    "});" & _
                    "</script><body style='color:#808000'>" & _
                    "<br><div>Get the TextBox value using Javascript...</div><br>" & _
                    "<form id='form1' onsubmit='return false;'>" & _
                    "<input id='txt1' name='txt1' value='Hello World!'>" & _
                    "<button id='btn1' type='submit'>Get</button>" & _
                    "</form>" & _
                    "</body></html>")
                    
            Case AsyncStatus_Error
                Set AsyncInfo = AsyncOperation
                MsgBox Hex$(AsyncInfo.ErrorCode) & vbNewLine & GetErrorMessage(AsyncInfo.ErrorCode), vbOKOnly + vbExclamation, App.Title
        End Select
    End Sub
    
    Private Sub ITypedEventHandlerWebViewControlScriptNotify_Invoke(ByVal Sender As IWebViewControl, ByVal Args As IWebViewControlScriptNotifyEventArgs)
        MsgBox GetStr(Args.Value), vbOKOnly + vbInformation, App.Title
        With Params
            .Clear
            .Append StrRef("txt1")
            .Append StrRef("Goodbye World!")
        End With
        Sender.InvokeScriptAsync StrRef("setQSValue"), Params
    End Sub
    After you close the MsgBox it executes InvokeScriptAsync to call your setQSValue JavaScript function and modify the contents of the text input on your form:

    Name:  WebView2.png
Views: 37
Size:  5.4 KB

    Here is the WebViewDemo.zip project if you want to take a look. It requires a reference to the WinRT TypeLib.

  17. #17
    Addicted Member
    Join Date
    Oct 2014
    Posts
    133

    Re: [VB6] cWebView2 — RC6-compatible WebView2 wrapper

    Hello! WQWETO. Thank you for providing cWebView2. I suggest adding a feature: automatically check if the WebView2 runtime is installed, and if it's not, automatically install the WebView2 runtime. Combined with a registration-free manifest, this would make it much easier and more convenient for end users.

  18. #18
    PowerPoster VanGoghGaming's Avatar
    Join Date
    Jan 2020
    Location
    Eve Online - Mining, Missions & Market Trading!
    Posts
    2,649

    Lightbulb Re: [VB6] cWebView2 — RC6-compatible WebView2 wrapper

    The WinRT WebView doesn't like it when your VB6 IDE runs elevated (as administrator) so you can either run it unelevated (if possible) or compile the executable and run that instead.

  19. #19
    Addicted Member saturnian's Avatar
    Join Date
    Dec 2017
    Location
    France
    Posts
    145

    Re: [VB6] cWebView2 — RC6-compatible WebView2 wrapper

    @VanGoghGaming
    I'm going to test your WinRT version, which looks very interesting.

    But what I like most about wqweto's version is its perfect compatibility with RC6, which makes all the code I've already written perfectly functional without any rewrites.

  20. #20
    PowerPoster VanGoghGaming's Avatar
    Join Date
    Jan 2020
    Location
    Eve Online - Mining, Missions & Market Trading!
    Posts
    2,649

    Talking Re: [VB6] cWebView2 — RC6-compatible WebView2 wrapper

    Yeah, the WinRT WebView is not nearly as feature-rich as WebView2 but on the other hand it's a lot more light-weight and doesn't require a separate loader DLL, so it can come in handy when you want some JavaScript interaction with a webpage. I haven't played with it before so I was just curious how it would fare with your example code.

  21. #21

    Thread Starter
    PowerPoster wqweto's Avatar
    Join Date
    May 2011
    Location
    Sofia, Bulgaria
    Posts
    6,200

    Re: [VB6] cWebView2 — RC6-compatible WebView2 wrapper

    Both issues fixed in latest release -- Match retvals to RC6 and Synchronous JS bridge and defer events which was quite difficult to crack!

    What's new

    • Synchronous JS bridgejsRun/jsProp/jsCallByName now return live JS object proxies (not JSON copies) over RC6's SetFuncObj bridge, so jsCallByName dispatches on objects obtained from jsRun/jsProp, matching RC6. jsCallByName is now fully implemented.
    • jsRun works inside event handlers — notification events (NavigationCompleted, DocumentComplete, TitleChanged, DOMContentLoaded, JSMessage, …) are now raised on a clean stack via a fire-once timer, so a blocking jsRun/jsProp/jsCallByName from inside them no longer deadlocks. NavigationCompleted/DocumentComplete fire after Navigate returns (matching RC6). Cancelable events (NavigationStarting, PermissionRequested, …) stay synchronous — use jsRunAsync there.
    • Public CallByName reworked to dispatch on JS object proxies too.


    Breaking change

    • The TitleChange event is renamed TitleChanged (matching the native DocumentTitleChanged). Update any WV_TitleChange handler to WV_TitleChanged.


    Download: VbWebView2 1.1.0

    cheers,
    </wqw>

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  



Click Here to Expand Forum to Full Width