From 98dca9d33fbc88da6a6d38b426269c867c84f266 Mon Sep 17 00:00:00 2001 From: woeoio Date: Tue, 17 Feb 2026 09:03:17 +0800 Subject: [PATCH 1/2] docs: add WebView2 package reference documentation --- .../Webview2/DeferredCallback.md | 473 ++++++++++ .../Webview2/Getting-started.md | 731 ++++++++++++++ docs/PackageReference/Webview2/README.md | 273 ++++++ .../Webview2/WebView2-Enumerations.md | 392 ++++++++ .../Webview2/WebView2-Events.md | 659 +++++++++++++ .../Webview2/WebView2-Methods.md | 888 ++++++++++++++++++ .../Webview2/WebView2-Properties.md | 666 +++++++++++++ docs/PackageReference/Webview2/WebView2.md | 325 +++++++ .../Webview2/WebView2EnvironmentOptions.md | 295 ++++++ .../Webview2/WebView2Header.md | 336 +++++++ .../Webview2/WebView2HeadersCollection.md | 233 +++++ .../Webview2/WebView2Request.md | 259 +++++ .../Webview2/WebView2RequestHeaders.md | 205 ++++ .../Webview2/WebView2Response.md | 470 +++++++++ .../Webview2/WebView2ResponseHeaders.md | 297 ++++++ docs/PackageReference/Webview2/index.md | 130 +++ docs/PackageReference/index.md | 15 + 17 files changed, 6647 insertions(+) create mode 100644 docs/PackageReference/Webview2/DeferredCallback.md create mode 100644 docs/PackageReference/Webview2/Getting-started.md create mode 100644 docs/PackageReference/Webview2/README.md create mode 100644 docs/PackageReference/Webview2/WebView2-Enumerations.md create mode 100644 docs/PackageReference/Webview2/WebView2-Events.md create mode 100644 docs/PackageReference/Webview2/WebView2-Methods.md create mode 100644 docs/PackageReference/Webview2/WebView2-Properties.md create mode 100644 docs/PackageReference/Webview2/WebView2.md create mode 100644 docs/PackageReference/Webview2/WebView2EnvironmentOptions.md create mode 100644 docs/PackageReference/Webview2/WebView2Header.md create mode 100644 docs/PackageReference/Webview2/WebView2HeadersCollection.md create mode 100644 docs/PackageReference/Webview2/WebView2Request.md create mode 100644 docs/PackageReference/Webview2/WebView2RequestHeaders.md create mode 100644 docs/PackageReference/Webview2/WebView2Response.md create mode 100644 docs/PackageReference/Webview2/WebView2ResponseHeaders.md create mode 100644 docs/PackageReference/Webview2/index.md create mode 100644 docs/PackageReference/index.md diff --git a/docs/PackageReference/Webview2/DeferredCallback.md b/docs/PackageReference/Webview2/DeferredCallback.md new file mode 100644 index 0000000..bfbd38f --- /dev/null +++ b/docs/PackageReference/Webview2/DeferredCallback.md @@ -0,0 +1,473 @@ +--- +title: Deferred Callback +parent: WebView2 Package +nav_order: 16 +--- + +# Deferred Callback Mechanism + +The WebView2 package provides a deferred event and callback mechanism to solve re-entrancy problems during event handling. When you need to call WebView2 control methods within an event handler, using the deferred mechanism can avoid potential deadlocks and crashes. + +## Overview + +### What is the Re-entrancy Problem? + +Re-entrancy refers to calling a method of the same object again during an event handler, causing recursive code execution. In WebView2, some event handlers may need to call WebView2 control methods, and direct calls can lead to: + +- Deadlocks +- Crashes +- Unexpected behavior +- Call stack overflow + +### How the Deferred Mechanism Works + +The deferred mechanism works in the following ways: + +1. **Deferred Execution**: Postpone event handling until after the current message loop completes +2. **Message Queue**: Use Windows message queue to schedule deferred execution +3. **Asynchronous Processing**: Avoid calling WebView2 methods directly in event handling context + +## WebView2 Control Related + +### UseDeferredEvents Property + +```vb +Public UseDeferredEvents As Boolean = True +``` + +Controls whether to use deferred event mode. Default value is `True`. + +| Value | Description | +| ------- | ---------------------------------------------------------- | +| `True` | Use deferred event mode (recommended) | +| `False` | Use synchronous event mode (may cause re-entrancy problems) | + +**Example:** + +```vb +Private Sub Form_Load() + ' Note: All WebView21 member operations must be done after WebView21_Ready() +End Sub + +Private Sub WebView21_Ready() + ' Recommended to use deferred event mode + WebView21.UseDeferredEvents = True +End Sub +``` + +### Events Supporting Deferred Mode + +The following events support deferred mode: + +| Event | Description | +| ---------------------- | ------------------------------- | +| `PermissionRequested` | Permission request event | +| `NavigationComplete` | Navigation complete event | +| `SourceChanged` | Source changed event | +| `DocumentTitleChanged` | Document title changed event | +| `ProcessFailed` | Process failed event | +| `DOMContentLoaded` | DOM load complete event | +| `ScriptDialogOpening` | Script dialog opening event | +| `DownloadStarting` | Download starting event | +| `WebResourceRequested` | Web resource request event | +| `NewWindowRequested` | New window request event | +| `Ready` | WebView2 ready event | +| `SuspendCompleted` | Suspend complete event | +| `SuspendFailed` | Suspend failed event | +| `PrintToPdfCompleted` | PDF print complete event | +| `PrintToPdfFailed` | PDF print failed event | +| `JsAsyncResult` | JS async result event | + +## Deferred Invocation for AddObject + +### UseDeferredInvoke Parameter + +```vb +Public Sub AddObject(ByVal ObjName As String, ByVal Object As Object, _ + ByVal UseDeferredInvoke As Boolean = False) +``` + +The `UseDeferredInvoke` parameter of the `AddObject` method controls the behavior when JavaScript calls VB objects. + +| Value | Description | +| ------- | ------------------------------------------------------------------------------- | +| `False` | Direct invocation, can return value to JavaScript, but may cause re-entrancy problems | +| `True` | Deferred invocation, avoids re-entrancy problems, returns value to JavaScript asynchronously via Promise | + +### Direct Invocation Mode (UseDeferredInvoke = False) + +```vb +' Twinbasic side +Public Function GetValue() As String + GetValue = "Hello from Twinbasic" +End Function + +Private Sub WebView21_Ready() + WebView21.AddObject "tbObjectInst", Me, False ' Direct invocation +End Sub +``` + +```javascript +// JavaScript side +var result = window.chrome.webview.hostObjects.tbObjectInst.GetValue(); +console.log(result); // Output: Hello from Twinbasic +``` + +**Advantages:** + +- Can return value to JavaScript +- Simple and direct invocation + +**Disadvantages:** + +- May cause re-entrancy problems +- Cannot call WebView2 methods during invocation + +**Use Cases:** + +- Only need to return simple data +- No need to access WebView2 during invocation + +### Deferred Invocation Mode (UseDeferredInvoke = True) + +```vb +' Twinbasic side +Public Function ProcessData(ByVal data As String) As String + Debug.Print "Processing data: " & data + ' Can safely call WebView2 methods here + WebView21.PostWebMessage "Processing complete: " & data + ProcessData = "Processing result: " & data +End Function + +Private Sub WebView21_Ready() + WebView21.AddObject "tbObjectInst", Me, True ' Deferred invocation +End Sub +``` + +```javascript +// JavaScript side +// Returns a Promise object, you can get the return value via .then() +window.chrome.webview.hostObjects.tbObjectInst + .ProcessData("test data") + .then(function (result) { + console.log("VB return value:", result); // Output: Processing result: test data + }) + .catch(function (error) { + console.error("Invocation error:", error); + }); + +// Use async/await syntax +async function callVB() { + try { + const result = + await window.chrome.webview.hostObjects.tbObjectInst.ProcessData( + "test data", + ); + console.log(result); + } catch (error) { + console.error(error); + } +} +``` + +**Advantages:** + +- Avoids re-entrancy problems +- Can call WebView2 methods in the method +- More safe and stable +- Returns value to JavaScript asynchronously via Promise + +**Disadvantages:** + +- Invocation is asynchronous, need to use Promise or async/await +- Slightly more latency compared to direct invocation + +**Use Cases:** + +- Need to call WebView2 in the method +- Can accept asynchronous return values +- Handle complex interaction logic + +## Internal Classes + +### WebView2DeferredCallback + +**Class ID:** `383FCA6A-9D0B-4F03-B4D1-F040D7588B91` + +Internal class for deferred callbacks, implements the `IScheduledCallback` interface. + +**Constructor:** + +```vb +Public Sub New(ByVal Control As IDeferredCallback, _ + ByVal EventName As String, _ + ByVal Args As stdole.IUnknown, _ + ByVal Deferral As ICoreWebView2Deferral) +``` + +**Supported Events:** + +- `NewWindowRequested` +- `PermissionRequested` +- `WebResourceRequested` +- `ScriptDialogOpening` +- `DownloadStarting` + +### WebView2DeferredRaiseEvent + +**Class ID:** `9B92FD8E-1F85-494F-BA97-02E2DDED0AD2` + +Internal class for deferred event raising, implements the `IScheduledCallback` interface. + +**Constructor:** + +```vb +Public Sub New(ByVal Control As WebView2, _ + ByVal EventName As String, _ + ParamArray Args() As Variant) +``` + +### IDeferredCallback Interface + +```vb +Interface IDeferredCallback + Sub NewWindowRequested(ByVal args As ICoreWebView2NewWindowRequestedEventArgs, _ + ByVal Deferral As ICoreWebView2Deferral) + Sub PermissionRequested(ByVal args As ICoreWebView2PermissionRequestedEventArgs, _ + ByVal Deferral As ICoreWebView2Deferral) + Sub WebResourceRequested(ByVal args As ICoreWebView2WebResourceRequestedEventArgs, _ + ByVal Deferral As ICoreWebView2Deferral) + Sub ScriptDialogOpening(ByVal args As ICoreWebView2ScriptDialogOpeningEventArgs, _ + ByVal Deferral As ICoreWebView2Deferral) + Sub DownloadStarting(ByVal args As ICoreWebView2DownloadStartingEventArgs, _ + ByVal Deferral As ICoreWebView2Deferral) +End Interface +``` + +## Usage Examples + +### Example 1: Execute JavaScript After Navigation Completes + +```vb +Private Sub WebView21_NavigationComplete(ByVal IsSuccess As Boolean, ByVal WebErrorStatus As Long) + If IsSuccess Then + ' In deferred mode, can safely call WebView2 methods + WebView21.ExecuteScript "document.body.style.backgroundColor = '#f0f0f0'" + Dim title As Variant + title = WebView21.JsProp("document.title") + Debug.Print "Page title: " & title + End If +End Sub +``` + +### Example 2: Call WebView2 Methods in Permission Request + +```vb +Private Sub WebView21_PermissionRequested(ByVal IsUserInitiated As Boolean, _ + ByRef State As wv2PermissionState, ByVal Uri As String, _ + ByVal PermissionKind As wv2PermissionKind) + + ' Decide based on permission type + Select Case PermissionKind + Case wv2Geolocation + ' Show dialog to ask user + If MsgBox("Allow access to location?", vbYesNo) = vbYes Then + State = wv2StateAllow + ' Can safely log in deferred mode + WebView21.PostWebMessage "Geolocation permission granted" + Else + State = wv2StateDeny + End If + Case wv2Camera + State = wv2StateDeny + End Select +End Sub +``` + +### Example 3: Script Dialog Handling + +```vb +Private Sub WebView21_ScriptDialogOpening(ByVal ScriptDialogKind As wv2ScriptDialogKind, _ + ByRef Accept As Boolean, ByVal ResultText As String, ByVal URI As String, _ + ByVal Message As String, ByVal DefaultText As String) + + Select Case ScriptDialogKind + Case wv2DialogAlert + ' Custom Alert dialog + Accept = True + MsgBox Message, vbInformation, "Web Page Notification" + + ' Can safely log in deferred mode + WebView21.PostWebMessage "Showing Alert: " & Message + + Case wv2DialogConfirm + ' Custom Confirm dialog + If MsgBox(Message, vbYesNo, "Confirm") = vbYes Then + Accept = True + WebView21.PostWebMessage "User clicked OK" + Else + Accept = False + WebView21.PostWebMessage "User clicked Cancel" + End If + + Case wv2DialogPrompt + ' Custom Prompt dialog + ResultText = InputBox(Message, "Input", DefaultText) + Accept = True + WebView21.PostWebMessage "User input: " & ResultText + End Select +End Sub +``` + +### Example 4: Mixed Use of Deferred and Non-Deferred Invocations + +```vb +Public Class Form1 + Public Function GetConfigValue(ByVal key As String) As String + ' This method needs to return value, use non-deferred invocation + Select Case key + Case "version" + GetConfigValue = "1.0" + Case "name" + GetConfigValue = "MyApp" + End Select + End Function + + Public Function HandleEvent(ByVal eventData As String) As String + ' This method uses deferred invocation, returns value to JavaScript asynchronously via Promise + Debug.Print "Event: " & eventData + ' Can safely call WebView2 methods + WebView21.PostWebMessage "Event processed" + HandleEvent = "Processing complete: " & eventData + End Function + + Private Sub WebView21_Ready() + ' Add two objects using different invocation modes + WebView21.AddObject "config", Me, False ' Non-deferred invocation + WebView21.AddObject "handler", Me, True ' Deferred invocation + End Sub +End Class +``` + +```javascript +// JavaScript side +// config object needs to return value, use non-deferred invocation (synchronous) +var version = + window.chrome.webview.hostObjects.config.GetConfigValue("version"); +console.log(version); // Output: 1.0 + +// handler object uses deferred invocation, get return value asynchronously via Promise +window.chrome.webview.hostObjects.handler + .HandleEvent("button_click") + .then(function (result) { + console.log("Processing result:", result); // Output: Processing complete: button_click + }) + .catch(function (error) { + console.error("Invocation error:", error); + }); + +// Use async/await syntax +async function callHandler() { + try { + const result = + await window.chrome.webview.hostObjects.handler.HandleEvent("submit"); + console.log(result); + } catch (error) { + console.error(error); + } +} +``` + +### Example 5: Web Resource Interception + +```vb +Private Sub WebView21_WebResourceRequested(ByVal Request As WebView2Request, _ + ByVal Response As WebView2Response) + + ' Intercept specific request + If InStr(Request.Uri, "/api/data") > 0 Then + ' Build custom response + Response.StatusCode = 200 + Response.ReasonPhrase = "OK" + Response.ContentUTF8 = "{""status"":""success""}" + Response.Headers.AppendHeader "Content-Type", "application/json" + + ' Can safely log in deferred mode + WebView21.PostWebMessage "Intercepted request: " & Request.Uri + End If +End Sub +``` + +## Best Practices + +### 1. Use Deferred Mode by Default + +```vb +Private Sub Form_Load() + ' Note: All WebView21 member operations must be done after WebView21_Ready() +End Sub + +Private Sub WebView21_Ready() + WebView21.UseDeferredEvents = True +End Sub +``` + +### 2. Choose AddObject Mode Based on Requirements + +```vb +' When need to return value +WebView21.AddObject "dataProvider", dataProvider, False + +' When don't need to return value +WebView21.AddObject "eventHandler", eventHandler, True +``` + +### 3. Avoid Blocking in Event Handlers + +```vb +Private Sub WebView21_NavigationComplete(ByVal IsSuccess As Boolean, ByVal WebErrorStatus As Long) + If IsSuccess Then + ' Don't perform time-consuming operations in event handler + ' Use deferred invocation or async processing + WebView21.JsRunAsync "initPage", FunctionAddress(OnPageInitComplete) + End If +End Sub +``` + +### 4. Error Handling + +```vb +Private Sub WebView21_WebResourceRequested(ByVal Request As WebView2Request, _ + ByVal Response As WebView2Response) + + On Error GoTo ErrorHandler + + ' Processing logic + Response.StatusCode = 200 + + Exit Sub + +ErrorHandler: + Debug.Print "Error: " & Err.Description + Response.StatusCode = 500 + Response.ReasonPhrase = "Internal Server Error" +End Sub +``` + +## Notes + +1. **Default Setting**: `UseDeferredEvents` defaults to `True`, which is the recommended setting. + +2. **Performance Impact**: Deferred events introduce a slight delay, but it's negligible for most applications. + +3. **Asynchronous Return Values**: Deferred object methods return values to JavaScript asynchronously via Promise, need to use `.then()` or `await` syntax to get them. + +4. **Asynchronous Nature**: Deferred invocations are asynchronous, pay attention to execution order. + +5. **Debugging Difficulty**: Deferred invocations increase debugging complexity, need to carefully track execution flow. + +6. **Memory Leaks**: Ensure proper cleanup of object references to avoid memory leaks. + +7. **Thread Safety**: Deferred invocations execute in the main thread's message queue, no need to worry about thread safety issues. + +8. **Event Order**: Deferred events execute after the current event handling completes, which may affect expected event order. diff --git a/docs/PackageReference/Webview2/Getting-started.md b/docs/PackageReference/Webview2/Getting-started.md new file mode 100644 index 0000000..4be8e38 --- /dev/null +++ b/docs/PackageReference/Webview2/Getting-started.md @@ -0,0 +1,731 @@ +--- +title: Quick Start +parent: WebView2 Package +nav_order: 3 +--- + +# WebView2 Quick Start Guide + +This guide will help you quickly get started with the twinBASIC WebView2 control. + +## Environment Setup + +### 1. Install WebView2 Runtime + +WebView2 requires Microsoft Edge WebView2 Runtime (Evergreen) to be installed. + +**Download URLs:** + +- Official download: [https://developer.microsoft.com/microsoft-edge/webview2/](https://developer.microsoft.com/microsoft-edge/webview2/) +- Evergreen Runtime: [https://go.microsoft.com/fwlink/p/?LinkId=2124703](https://go.microsoft.com/fwlink/p/?LinkId=2124703) + +> **Note:** If you are using Windows 7, please download the WebView2 Runtime that supports Windows 7 from: +> [https://gitcode.com/woeoio/tbman/releases/Webview2Runtime](https://gitcode.com/woeoio/tbman/releases/Webview2Runtime) + +**Check if already installed:** + +You can verify whether WebView2 Runtime is installed by checking the default installation directory and registry. + +```vb +Private Function IsWebView2Installed() As Boolean + Dim wsh As Object + Dim regValue As String + Dim installPath As String + Dim tempPath As String + Dim found As Boolean + + found = False + Set wsh = CreateObject("WScript.Shell") + + ' ===== Method 1: Improved Registry Check ===== + On Error Resume Next ' Only used for registry reads + + ' Check 64-bit system (WOW6432Node) + regValue = "" + regValue = wsh.RegRead("HKEY_LOCAL_MACHINE\SOFTWARE\WOW6432Node\Microsoft\EdgeUpdate\Clients\{F3017226-FE2A-4295-8BDF-00C3A9A7E4C5}\pv") + If Len(regValue) > 0 Then + found = True + GoTo CleanUp + End If + + ' Check 32-bit system (without WOW6432Node) + regValue = "" + regValue = wsh.RegRead("HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\EdgeUpdate\Clients\{F3017226-FE2A-4295-8BDF-00C3A9A7E4C5}\pv") + If Len(regValue) > 0 Then + found = True + GoTo CleanUp + End If + + ' Check user-level installation + regValue = "" + regValue = wsh.RegRead("HKEY_CURRENT_USER\SOFTWARE\Microsoft\EdgeUpdate\Clients\{F3017226-FE2A-4295-8BDF-00C3A9A7E4C5}\pv") + If Len(regValue) > 0 Then + found = True + GoTo CleanUp + End If + + On Error GoTo 0 ' Restore normal error handling + + ' ===== Method 2: Improved File System Check ===== + ' Check 64-bit program directory + installPath = Environ("ProgramFiles(x86)") & "\Microsoft\EdgeWebView\Application\" + If Dir(installPath, vbDirectory) <> "" Then + ' Check if directory contains actual DLL files + tempPath = Dir(installPath & "*.dll") + If tempPath <> "" Then + found = True + GoTo CleanUp + End If + End If + + ' Check user directory + installPath = Environ("LOCALAPPDATA") & "\Microsoft\EdgeWebView\Application\" + If Dir(installPath, vbDirectory) <> "" Then + ' Check if directory contains actual DLL files + tempPath = Dir(installPath & "*.dll") + If tempPath <> "" Then + found = True + End If + End If + +CleanUp: + IsWebView2Installed = found + Set wsh = Nothing +End Function + +' Return WebView2 version number (if installed), otherwise return empty string +Private Function GetWebView2Version() As String + Dim wsh As Object + Dim regKeys(1 To 3) As String + Dim i As Integer + + regKeys(1) = "HKEY_LOCAL_MACHINE\SOFTWARE\WOW6432Node\Microsoft\EdgeUpdate\Clients\{F3017226-FE2A-4295-8BDF-00C3A9A7E4C5}\pv" + regKeys(2) = "HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\EdgeUpdate\Clients\{F3017226-FE2A-4295-8BDF-00C3A9A7E4C5}\pv" + regKeys(3) = "HKEY_CURRENT_USER\SOFTWARE\Microsoft\EdgeUpdate\Clients\{F3017226-FE2A-4295-8BDF-00C3A9A7E4C5}\pv" + + Set wsh = CreateObject("WScript.Shell") + On Error Resume Next + + For i = 1 To 3 + GetWebView2Version = wsh.RegRead(regKeys(i)) + If Len(GetWebView2Version) > 0 Then + Exit For + End If + Next i + + On Error GoTo 0 + Set wsh = Nothing +End Function +``` + +### 2. Reference WebView2 Package + +Reference the WebView2 package in your twinBASIC project: + +1. Open Project Settings +2. Select "Packages/References" +3. Add `WebView2Package` + +## Basic Usage + +### Example 1: Display a Web Page + +```vb +' Form1.frm +Option Explicit + +Private WithEvents WebView21 As WebView2 + +Private Sub Form_Load() + ' Create WebView2 control + Set WebView21 = Controls.Add("WebView2.WebView2", "WebView21") + + ' Set position and size + With WebView21 + .Visible = True + .Move 0, 0, ScaleWidth, ScaleHeight + .DocumentURL = "https://www.twinbasic.com" + End With +End Sub + +Private Sub WebView21_Ready() + Debug.Print "WebView2 is ready" +End Sub + +Private Sub Form_Resize() + If WebView21 Is Nothing Then Exit Sub + WebView21.Move 0, 0, ScaleWidth, ScaleHeight +End Sub +``` + +### Example 2: Design-Time Usage + +If you've added the WebView2 control to the form designer: + +```vb +Private Sub Form_Load() + ' Note: All WebView21 member operations must be done after WebView21_Ready() +End Sub + +Private Sub WebView21_Ready() + ' Set initial URL + WebView21.DocumentURL = "https://www.example.com" +End Sub + +Private Sub WebView21_NavigationComplete(ByVal IsSuccess As Boolean, ByVal WebErrorStatus As Long) + If IsSuccess Then + Debug.Print "Page loaded successfully" + Debug.Print "Title: " & WebView21.DocumentTitle + Else + Debug.Print "Page loading failed, error code: " & WebErrorStatus + End If +End Sub +``` + +## Navigation Control + +### Add Navigation Buttons + +```vb +Private WithEvents cmdBack As CommandButton +Private WithEvents cmdForward As CommandButton +Private WithEvents cmdRefresh As CommandButton +Private WithEvents txtUrl As TextBox +Private WithEvents cmdGo As CommandButton + +Private Sub Form_Load() + ' Create navigation buttons + Set cmdBack = Controls.Add("VB.CommandButton", "cmdBack") + cmdBack.Caption = "Back" + cmdBack.Move 10, 10, 60, 30 + + Set cmdForward = Controls.Add("VB.CommandButton", "cmdForward") + cmdForward.Caption = "Forward" + cmdForward.Move 80, 10, 60, 30 + + Set cmdRefresh = Controls.Add("VB.CommandButton", "cmdRefresh") + cmdRefresh.Caption = "Refresh" + cmdRefresh.Move 150, 10, 60, 30 + + ' Create URL input box + Set txtUrl = Controls.Add("VB.TextBox", "txtUrl") + txtUrl.Move 220, 10, 300, 30 + txtUrl.Text = "https://www.twinbasic.com" + + ' Create Go button + Set cmdGo = Controls.Add("VB.CommandButton", "cmdGo") + cmdGo.Caption = "Go" + cmdGo.Move 530, 10, 60, 30 + + ' Create WebView2 control + Set WebView21 = Controls.Add("WebView2.WebView2", "WebView21") + With WebView21 + .Visible = True + .Move 0, 50, ScaleWidth, ScaleHeight - 50 + End With +End Sub + +Private Sub cmdGo_Click() + If Len(txtUrl.Text) > 0 Then + WebView21.Navigate txtUrl.Text + End If +End Sub + +Private Sub cmdBack_Click() + If WebView21.CanGoBack Then + WebView21.GoBack + End If +End Sub + +Private Sub cmdForward_Click() + If WebView21.CanGoForward Then + WebView21.GoForward + End If +End Sub + +Private Sub cmdRefresh_Click() + WebView21.Reload +End Sub + +Private Sub WebView21_SourceChanged(ByVal IsNewDocument As Boolean) + txtUrl.Text = WebView21.DocumentURL +End Sub +``` + +## JavaScript Interaction + +### Execute JavaScript + +```vb +Private Sub WebView21_DOMContentLoaded() + ' Modify page background color + WebView21.ExecuteScript "document.body.style.backgroundColor = '#f0f0f0'" + + ' Get page title + Dim title As Variant + title = WebView21.JsProp("document.title") + Debug.Print "Page title: " & title +End Sub +``` + +### Call JavaScript Functions + +```vb +Private Sub WebView21_DOMContentLoaded() + ' Call page function + Dim result As Variant + result = WebView21.JsRun("getWindowWidth") + Debug.Print "Window width: " & result +End Sub +``` + +### Asynchronous JavaScript Invocation + +```vb +Private Sub WebView21_Ready() + ' Async JavaScript invocation + Dim token As LongLong + token = WebView21.JsRunAsync("fetchUserData", "user123") + Debug.Print "Async invocation Token: " & token +End Sub + +Private Sub WebView21_JsAsyncResult(ByVal Result As Variant, Token As LongLong, ErrString As String) + Debug.Print "Async result Token: " & Token + If Len(ErrString) > 0 Then + Debug.Print "Error: " & ErrString + Else + Debug.Print "Result: " & Result + End If +End Sub +``` + +## Twinbasic and JavaScript Communication + +### Send Message from Twinbasic to JavaScript + +```vb +' Twinbasic side +Private Sub btnSendMessage_Click() + WebView21.PostWebMessage "Hello from Twinbasic!" + WebView21.PostWebMessage Array("data1", "data2", 123) +End Sub +``` + +```javascript +// JavaScript side (in web page) +window.chrome.webview.addEventListener("message", function (e) { + console.log("Received message:", e.data); + // Process message + if (typeof e.data === "string") { + alert(e.data); + } else if (Array.isArray(e.data)) { + console.log("Array:", e.data); + } +}); +``` + +### Send Message from JavaScript to Twinbasic + +```javascript +// JavaScript side +window.chrome.webview.postMessage({ + type: "button_click", + buttonId: "submit", + timestamp: Date.now(), +}); +``` + +```vb +' Twinbasic side +Private Sub WebView21_JsMessage(ByVal Message As Variant) + Debug.Print "Received JS message: " & Message + + ' Process JSON object + If TypeName(Message) = "Object" Then + Debug.Print "Type: " & Message("type") + Debug.Print "Button ID: " & Message("buttonId") + End If +End Sub +``` + +## Object Sharing + +### Expose Twinbasic Objects to JavaScript + +```vb +' Twinbasic class module - tbObjectInst.twin +Public Function GetUserName() As String + GetUserName = "John Doe" +End Function + +Public Sub ShowMessage(ByVal msg As String) + MsgBox msg, vbInformation, "From Twinbasic" +End Sub + +Public Function Calculate(ByVal a As Double, ByVal b As Double) As Double + Calculate = a + b +End Function +``` + +```vb +' Main form +Private WithEvents WebView21 As WebView2 +Private vbObj As tbObjectInst + +Private Sub WebView21_Ready() + ' Create object + Set vbObj = New tbObjectInst + + ' Expose to JavaScript (direct invocation, can return value) + WebView21.AddObject "tbObjectInst", vbObj, False + + ' Expose to JavaScript (deferred invocation, returns value asynchronously via Promise) + WebView21.AddObject "vbHandler", vbObj, True +End Sub +``` + +```javascript +// JavaScript side +// Call Twinbasic method (needs return value, direct invocation) +var userName = window.chrome.webview.hostObjects.tbObjectInst.GetUserName(); +console.log(userName); // Output: John Doe + +var result = window.chrome.webview.hostObjects.tbObjectInst.Calculate(10, 20); +console.log(result); // Output: 30 + +// Call Twinbasic method (deferred invocation, returns value asynchronously via Promise) +window.chrome.webview.hostObjects.vbHandler + .ShowMessage("Test message") + .then(function (returnValue) { + console.log("Twinbasic return value:", returnValue); + }) + .catch(function (error) { + console.error("Invocation error:", error); + }); + +// Use async/await syntax +async function callVBHandler() { + try { + const result = await window.chrome.webview.hostObjects.vbHandler.Calculate( + 5, + 3, + ); + console.log("Calculation result:", result); + } catch (error) { + console.error(error); + } +} +``` + +## Permission Handling + +```vb +Private Sub WebView21_PermissionRequested(ByVal IsUserInitiated As Boolean, _ + ByRef State As wv2PermissionState, ByVal Uri As String, _ + ByVal PermissionKind As wv2PermissionKind) + + Select Case PermissionKind + Case wv2ClipboardRead + ' Allow clipboard read + State = wv2StateAllow + Debug.Print "Allowed clipboard access: " & Uri + + Case wv2Geolocation + ' Ask user if they allow geolocation + If MsgBox("Web page requests access to location, allow?", vbYesNo + vbQuestion) = vbYes Then + State = wv2StateAllow + Debug.Print "Allowed location access: " & Uri + Else + State = wv2StateDeny + Debug.Print "Denied location access: " & Uri + End If + + Case wv2Camera, wv2Microphone + ' Deny camera and microphone + State = wv2StateDeny + Debug.Print "Denied " & PermissionKind & ": " & Uri + + Case Else + ' Other permissions use default behavior + State = wv2StateDefault + End Select +End Sub +``` + +## Load Custom HTML + +```vb +Private Sub Form_Load() + ' Note: All WebView21 member operations must be done after WebView21_Ready() +End Sub + +Private Sub WebView21_Ready() + ' Create HTML content + Dim html As String + html = "" & vbCrLf + html = html & "" & vbCrLf + html = html & "" & vbCrLf + html = html & " " & vbCrLf + html = html & " Local HTML" & vbCrLf + html = html & " " & vbCrLf + html = html & "" & vbCrLf + html = html & "" & vbCrLf + html = html & "

Welcome to WebView2

" & vbCrLf + html = html & "

This is a local HTML page

" & vbCrLf + html = html & " " & vbCrLf + html = html & " " & vbCrLf + html = html & "" & vbCrLf + html = html & "" + + ' Load HTML + WebView21.NavigateToString html +End Sub +``` + +## Load Local Files + +```vb +Private Sub Form_Load() + ' Note: All WebView21 member operations must be done after WebView21_Ready() +End Sub + +Private Sub WebView21_Ready() + ' Method 1: Use file path + WebView21.Navigate "file:///C:/Projects/MyApp/index.html" + + ' Method 2: Use virtual host mapping + WebView21.SetVirtualHostNameToFolderMapping "app.local", "C:\Projects\MyApp", wv2ResourceAllow + WebView21.Navigate "https://app.local/index.html" +End Sub +``` + +### Comparison of Two Methods + +| Feature | file:// protocol | Virtual host mapping | +| ------------- | ----------------------------- | --------------------------------------- | +| Protocol | file:// | https:// | +| Domain | File path | Custom domain name | +| Security | More restrictions | Less restrictions (follows HTTPS rules) | +| Compatibility | Some frameworks don't support | Widely supported | + +### Core Advantages of Virtual Host Mapping + +#### 1. Solve Frontend Framework Protocol Restrictions + +Many modern frontend frameworks and libraries, for security reasons, **prohibit or restrict running under the `file://` protocol**, including: + +- React, Vue, Angular and other frameworks' features +- Service Worker (must be under HTTPS or localhost) +- Web Workers (some restrictions) +- IndexedDB (disabled under file:// in some browsers) +- Fetch API cross-origin requests + +Virtual host mapping uses `https://` protocol, **completely avoiding these restrictions**. + +#### 2. Simulate Web Server Environment + +- **No real server needed**: No need to install nginx, Apache, etc. +- **No port occupation**: Maps directly to local folder +- **Custom domain**: Can set memorable domain names (like `app.local`, `dev.local`) +- **Follows HTTPS rules**: Enjoy security features of modern web standards + +#### 3. Better Resource Loading Experience + +```vb +' file:// method may have issues +WebView21.Navigate "file:///C:/Projects/MyApp/index.html" +' Relative path resource loading may be restricted +' may fail + +' Virtual host mapping method +WebView21.SetVirtualHostNameToFolderMapping "app.local", "C:\Projects\MyApp", wv2ResourceAllow +WebView21.Navigate "https://app.local/index.html" +' All resources loaded via https://app.local/, consistent with real server +``` + +#### 4. Access Control Permissions + +The second parameter of virtual host mapping can set resource access permissions: + +```vb +' wv2ResourceAllow - Allow all access +' wv2ResourceDeny - Deny access +' wv2ResourceDenyCors - Deny CORS requests +``` + +### Typical Use Cases + +#### Scenario 1: Developing Single Page Application (SPA) + +```vb +Private Sub Form_Load() + ' Note: All WebView21 member operations must be done after WebView21_Ready() +End Sub + +Private Sub WebView21_Ready() + ' Vue/React projects use virtual host mapping + WebView21.SetVirtualHostNameToFolderMapping "myapp.dev", "C:\MyVueApp\dist", wv2ResourceAllow + WebView21.Navigate "https://myapp.dev/index.html" +End Sub +``` + +#### Scenario 2: Multiple Independent Applications + +```vb +Private Sub Form_Load() + ' Note: All WebView21 member operations must be done after WebView21_Ready() +End Sub + +Private Sub WebView21_Ready() + ' Run multiple applications simultaneously + WebView21.SetVirtualHostNameToFolderMapping "admin.local", "C:\Apps\admin", wv2ResourceAllow + WebView21.SetVirtualHostNameToFolderMapping "api.local", "C:\Apps\api-docs", wv2ResourceAllow + + ' Switch to load different applications + WebView21.Navigate "https://admin.local/index.html" +End Sub +``` + +#### Scenario 3: Avoid Cross-Origin Issues + +```javascript +// Using file://, fetch requests may be blocked +fetch("data.json"); // May fail under file:// + +// Using virtual host mapping, works like on a real server +fetch("/data.json"); // Works normally, uses https://app.local/data.json +``` + +### Nature of Virtual Host Mapping + +Virtual host mapping maps a local folder to a custom HTTPS domain name, making the browser think it's accessing a real web server. + +### Best Practices + +- For simple static HTML, use `file://` +- For modern frontend apps, SPAs, or scenarios needing Service Worker, etc., **strongly recommend using virtual host mapping** +- When publishing to production, just replace with real HTTPS server addresses + +## Print to PDF + +```vb +Private Sub btnSaveToPdf_Click() + Dim savePath As String + savePath = "C:\Temp\output.pdf" + + ' Check if feature is supported + If WebView21.SupportsPdfFeatures Then + ' Print to PDF + WebView21.PrintToPdf savePath, _ + Orientation:=wv2PrintPortrait, _ + ShouldPrintBackgrounds:=True, _ + MarginTop:=20, _ + MarginBottom:=20, _ + MarginLeft:=20, _ + MarginRight:=20 + + Debug.Print "PDF printing..." + Else + MsgBox "Current WebView2 version does not support PDF features", vbExclamation + End If +End Sub + +Private Sub WebView21_PrintToPdfCompleted() + MsgBox "PDF printing complete!", vbInformation +End Sub + +Private Sub WebView21_PrintToPdfFailed() + MsgBox "PDF printing failed!", vbExclamation +End Sub +``` + +## Developer Tools + +```vb +Private Sub cmdOpenDevTools_Click() + ' Open developer tools + WebView21.OpenDevToolsWindow +End Sub + +Private Sub cmdInspectPage_Click() + ' Call DevTools protocol method + If WebView21.AreDevToolsEnabled Then + WebView21.CallDevToolsProtocolMethod "Runtime.enable", "{}", "enableRuntime" + End If +End Sub + +Private Sub WebView21_DevToolsProtocolResponse(ByVal CustomEventId As Variant, ByVal JsonResponse As String) + Debug.Print "DevTools response [" & CustomEventId & "]: " & JsonResponse +End Sub +``` + +## Common Issues + +### 1. Control Not Showing + +```vb +' Make sure to set Visible and position +Private Sub Form_Load() + Set WebView21 = Controls.Add("WebView2.WebView2", "WebView21") + With WebView21 + .Visible = True + .Move 0, 0, ScaleWidth, ScaleHeight + End With +End Sub +``` + +### 2. Page Loading Failed + +```vb +Private Sub WebView21_Error(ByVal code As Long, ByVal msg As String) + Debug.Print "Error code: " & code + Debug.Print "Error message: " & msg + + ' Check if WebView2 Runtime is installed + If code = -1 Then + MsgBox "WebView2 Runtime is not installed" & vbCrLf & vbCrLf & msg, vbCritical + End If +End Sub +``` + +### 3. JavaScript Call Timeout + +```vb +Private Sub Form_Load() + ' Note: All WebView21 member operations must be done after WebView21_Ready() +End Sub + +Private Sub WebView21_Ready() + ' Set JavaScript call timeout (seconds) + WebView21.JsCallTimeOutSeconds = 30 +End Sub +``` + +### 4. Re-entrancy Problems + +```vb +Private Sub Form_Load() + ' Note: All WebView21 member operations must be done after WebView21_Ready() +End Sub + +Private Sub WebView21_Ready() + ' Use deferred event mode to avoid re-entrancy problems + WebView21.UseDeferredEvents = True +End Sub +``` + +## Next Steps + +- Read [WebView2 Control](./WebView2.md) to learn all properties, methods, and events +- Read [Environment Options](./WebView2EnvironmentOptions.md) to configure WebView2 environment +- Read [Enumeration Types](./Enumerations.md) to learn all enumeration values +- Read [Deferred Callback](./DeferredCallback.md) to understand how to handle re-entrancy problems +- Read [Re-entrancy Issues](./Re-entrancy.md) for detailed explanation of re-entrancy problems + diff --git a/docs/PackageReference/Webview2/README.md b/docs/PackageReference/Webview2/README.md new file mode 100644 index 0000000..9b37202 --- /dev/null +++ b/docs/PackageReference/Webview2/README.md @@ -0,0 +1,273 @@ +--- +title: Documentation Overview +parent: WebView2 Package +nav_order: 2 +--- + +# WebView2 Technical Documentation + +twinBASIC WebView2 package provides complete Microsoft Edge WebView2 control integration, enabling you to embed modern web content in twinBASIC applications and achieve bidirectional interaction. + +## Documentation Index + +### Core Documents + +| Document | Description | +| ------------------------------------ | ---------------------------------------------- | +| [Getting Started Guide](./Getting-started.md) | Quick start with WebView2 control | +| [Index](./index.md) | Documentation index and functionality overview | + +### Class References + +| Document | Description | +| ----------------------------------------------- | -------------------------------------------- | +| [WebView2 Control](./WebView2.md) | Main control class, complete reference of all properties, methods, and events | +| [Environment Options](./WebView2EnvironmentOptions.md) | WebView2 environment configuration options | + +### HTTP Related + +| Document | Description | +| -------------------------------------------- | ------------------------- | +| [HTTP Request](./WebView2Request.md) | Web resource request object| +| [HTTP Response](./WebView2Response.md) | Web resource response object| +| [Request Headers](./WebView2RequestHeaders.md)| HTTP request header management | +| [Response Headers](./WebView2ResponseHeaders.md)| HTTP response header management| +| [Header Collection](./WebView2HeadersCollection.md)| HTTP header collection enumeration | +| [Header Info](./WebView2Header.md) | Single HTTP header information | + +### Advanced Topics + +| Document | Description | +| ------------------------------------ | ------------------------------------------- | +| [Enumeration Types](./Enumerations.md)| All enumeration type definitions and descriptions | +| [Deferred Callback](./DeferredCallback.md) | Deferred event and callback mechanism (re-entrancy issues) | + +## Quick Navigation + +### I Want to... + +#### Display a Web Page + +```vb +WebView21.Navigate "https://www.example.com" +``` + +→ Refer to [WebView2 Control - Navigation Methods](./WebView2.md#navigation-methods) + +#### Execute JavaScript + +```vb +Dim result As Variant +result = WebView21.JsRun("document.title") +``` + +→ Refer to [WebView2 Control - JavaScript Interaction](./WebView2.md#javascript-interaction-methods) + +#### Communicate Between Twinbasic and JavaScript + +```vb +' Twinbasic sends to JavaScript +WebView21.PostWebMessage "Hello!" + +' JavaScript sends to Twinbasic +window.chrome.webview.postMessage("Hello from JS"); +``` + +→ Refer to [WebView2 Control - Message Passing](./WebView2.md#message-passing-methods) + +#### Intercept HTTP Requests + +```vb +WebView21.AddWebResourceRequestedFilter "*://*/*.png", wv2Image + +Private Sub WebView21_WebResourceRequested(ByVal Request As WebView2Request, _ + ByVal Response As WebView2Response) + ' Handle request +End Sub +``` + +→ Refer to [WebView2 Control - Web Resource Interception](./WebView2.md#web-resource-interception-methods) + +#### Customize Right-Click Menu + +```vb +Private Sub WebView21_UserContextMenu(X As Single, Y As Single) + PopupMenu mnuCustomContext, vbPopupMenuRightButton, X, Y +End Sub +``` + +→ Refer to [WebView2 Control - Events](./WebView2.md#user-interaction-events) + +#### Print to PDF + +```vb +WebView21.PrintToPdf "C:\output.pdf" +``` + +→ Refer to [WebView2 Control - Advanced Features](./WebView2.md#advanced-features-methods) + +#### Configure Environment Options + +```vb +WebView21.EnvironmentOptions.UserDataFolder = "C:\MyApp\Data" +WebView21.EnvironmentOptions.Language = "en-US" +``` + +→ Refer to [Environment Options](./WebView2EnvironmentOptions.md) + +## Core Class Diagram + +``` +WebView2 (Main Control) +├── WebView2EnvironmentOptions (Environment Configuration) +├── WebView2Request (HTTP Request) +│ └── WebView2RequestHeaders (Request Headers) +│ └── WebView2HeadersCollection (Header Collection) +│ └── WebView2Header (Single Header) +└── WebView2Response (HTTP Response) + └── WebView2ResponseHeaders (Response Headers) + └── WebView2HeadersCollection (Header Collection) + └── WebView2Header (Single Header) +``` + +## Main Functionality Modules + +### 1. Web Content Display + +- ✅ Load URL web pages +- ✅ Load custom HTML strings +- ✅ Virtual host mapping +- ✅ PDF export + +### 2. Navigation Control + +- ✅ Forward/backward navigation +- ✅ Page refresh +- ✅ Custom HTTP requests (POST, Headers) + +### 3. JavaScript Interaction + +- ✅ Execute JavaScript code +- ✅ Synchronously call JS functions +- ✅ Asynchronously call JS functions +- ✅ Bidirectional message passing + +### 4. Object Sharing + +- ✅ Expose COM objects to JavaScript +- ✅ Deferred invocation mode (avoid re-entrancy) + +### 5. Event Handling + +- ✅ Navigation events +- ✅ Permission request events +- ✅ Script dialog events +- ✅ Download events +- ✅ Web resource interception + +### 6. Advanced Features + +- ✅ Developer tools +- ✅ DevTools protocol +- ✅ Download manager +- ✅ Task manager +- ✅ Audio control +- ✅ Suspend/resume + +## Development Workflow + +### Step 1: Environment Setup + +1. Install WebView2 Runtime +2. Reference WebView2 package +3. Add WebView2 control to form + +→ Refer to [Getting Started](./Getting-started.md) + +### Step 2: Basic Navigation + +```vb +Private Sub Form_Load() + ' Note: All WebView21 member operations must be done after WebView21_Ready() +End Sub + +Private Sub WebView21_Ready() + WebView21.DocumentURL = "https://www.example.com" +End Sub + +Private Sub WebView21_NavigationComplete(ByVal IsSuccess As Boolean, _ + ByVal WebErrorStatus As Long) + ' Page loading complete +End Sub +``` + +### Step 3: JavaScript Interaction + +```vb +' Execute JS +WebView21.ExecuteScript "document.body.style.background = 'red'" + +' Get JS return value +Dim title As Variant +title = WebView21.JsProp("document.title") +``` + +### Step 4: Bidirectional Communication + +```vb +' Twinbasic sends to JavaScript +WebView21.PostWebMessage "Hello" + +Private Sub WebView21_JsMessage(ByVal Message As Variant) + ' Receive JavaScript message +End Sub +``` + +### Step 5: Advanced Features + +- Intercept HTTP requests +- Customize right-click menu +- Print PDF +- Virtual host mapping + +## Common Questions + +### 1. Control Not Displaying + +Make sure to set `Visible = True` and properly set position and size. + +### 2. Page Loading Failed + +Check if WebView2 Runtime is installed and review the `Error` event. + +### 3. JavaScript Call Timeout + +Set `JsCallTimeOutSeconds` property to increase timeout. + +### 4. Re-entrancy Problems + +Use `UseDeferredEvents = True` and use `UseDeferredInvoke = True` in `AddObject`. + +### 5. Permission Requests + +Handle permission requests in the `PermissionRequested` event. + +## Dependency Requirements + +- Windows 7 SP1 or higher +- WebView2 Runtime (Evergreen) 86.0.616.0 or higher + +## License + +The WebView2 package follows its own license terms, see the LICENCE.md file in the package for details. + +## Feedback and Support + +For questions or suggestions, please provide feedback through: + +- Submit an Issue +- Visit twinBASIC community + +## Documentation Updates + +Last updated: February 15, 2026 diff --git a/docs/PackageReference/Webview2/WebView2-Enumerations.md b/docs/PackageReference/Webview2/WebView2-Enumerations.md new file mode 100644 index 0000000..a03345f --- /dev/null +++ b/docs/PackageReference/Webview2/WebView2-Enumerations.md @@ -0,0 +1,392 @@ +--- +title: Enumerations +parent: WebView2 Package +nav_order: 8 +--- + +# WebView2 Enumeration Types + +This document describes all enumeration types defined in the WebView2 package. + +## wv2PermissionKind + +Permission type enumeration, used in `PermissionRequested` event. + +```vb +Enum wv2PermissionKind + wv2UnknownPermission = 0 + wv2Microphone = 1 + wv2Camera = 2 + wv2Geolocation = 3 + wv2Notifications = 4 + wv2Sensors = 5 + wv2ClipboardRead = 6 +End Enum +``` + +| Value | Name | Description | +| ----- | ----------------------- | ------------------------------------ | +| 0 | `wv2UnknownPermission` | Unknown permission | +| 1 | `wv2Microphone` | Microphone access permission | +| 2 | `wv2Camera` | Camera access permission | +| 3 | `wv2Geolocation` | Geolocation access permission | +| 4 | `wv2Notifications` | Notification permission | +| 5 | `wv2Sensors` | Sensor access permission | +| 6 | `wv2ClipboardRead` | Clipboard read permission | + +**Usage Example:** + +```vb +Private Sub WebView21_PermissionRequested(ByVal IsUserInitiated As Boolean, _ + ByRef State As wv2PermissionState, ByVal Uri As String, _ + ByVal PermissionKind As wv2PermissionKind) + + Select Case PermissionKind + Case wv2Microphone + State = wv2StateAllow + Case wv2Camera + State = wv2StateDeny + Case wv2Geolocation + State = wv2StateDefault + End Select +End Sub +``` + +--- + +## wv2PermissionState + +Permission state enumeration, used in `PermissionRequested` event. + +```vb +Enum wv2PermissionState + wv2StateDefault = 0 + wv2StateAllow = 1 + wv2StateDeny = 2 +End Enum +``` + +| Value | Name | Description | +| ----- | ----------------- | ----------------------------------------------- | +| 0 | `wv2StateDefault` | Use default behavior (usually prompts the user) | +| 1 | `wv2StateAllow` | Allow permission request | +| 2 | `wv2StateDeny` | Deny permission request | + +--- + +## wv2ErrorStatus + +Web error status enumeration, used in `NavigationComplete` event. + +```vb +Enum wv2ErrorStatus + wv2StateUnknown = 0 + wv2CertificateCommonNameIsIncorrect = 1 + wv2CertificateExpired = 2 + wv2ClientCertificateContainsErrors = 3 + wv2CertificateRevoked = 4 + wv2CertificateIsInvalid = 5 + wv2ServerUnreachable = 6 + wv2Timeout = 7 + wv2ErrorHttpInvalidServerResponse = 8 + wv2ConnectionAborted = 9 + wv2ConnectionReset = 10 + wv2Disconnected = 11 + wv2CannotConnect = 12 + wv2HostNameNotResolved = 13 + wv2OperationCanceled = 14 + wv2RedirectFailed = 15 + wv2UnexpectedError = 16 + wv2ValidAuthenticationCredentialsRequired = 17 + wv2ValidProxyAuthenticationRequired = 18 +End Enum +``` + +| Value | Name | Description | +| ----- | ------------------------------------------- | --------------------------------------------- | +| 0 | `wv2StateUnknown` | Unknown error | +| 1 | `wv2CertificateCommonNameIsIncorrect` | Certificate common name is incorrect | +| 2 | `wv2CertificateExpired` | Certificate has expired | +| 3 | `wv2ClientCertificateContainsErrors` | Client certificate contains errors | +| 4 | `wv2CertificateRevoked` | Certificate has been revoked | +| 5 | `wv2CertificateIsInvalid` | Certificate is invalid | +| 6 | `wv2ServerUnreachable` | Server unreachable | +| 7 | `wv2Timeout` | Connection timeout | +| 8 | `wv2ErrorHttpInvalidServerResponse` | HTTP invalid server response | +| 9 | `wv2ConnectionAborted` | Connection aborted | +| 10 | `wv2ConnectionReset` | Connection reset | +| 11 | `wv2Disconnected` | Disconnected | +| 12 | `wv2CannotConnect` | Cannot connect | +| 13 | `wv2HostNameNotResolved` | Host name cannot be resolved | +| 14 | `wv2OperationCanceled` | Operation canceled | +| 15 | `wv2RedirectFailed` | Redirect failed | +| 16 | `wv2UnexpectedError` | Unexpected error | +| 17 | `wv2ValidAuthenticationCredentialsRequired` | Valid authentication credentials required | +| 18 | `wv2ValidProxyAuthenticationRequired` | Valid proxy authentication required | + +**Usage Example:** + +```vb +Private Sub WebView21_NavigationComplete(ByVal IsSuccess As Boolean, _ + ByVal WebErrorStatus As Long) + + If Not IsSuccess Then + Select Case WebErrorStatus + Case wv2Timeout + MsgBox "Connection timeout!" + Case wv2HostNameNotResolved + MsgBox "Cannot resolve host name!" + Case Else + MsgBox "Navigation error: " & WebErrorStatus + End Select + End If +End Sub +``` + +--- + +## wv2KeyEventKind + +Keyboard event type enumeration, used in `AcceleratorKeyPressed` event. + +```vb +Enum wv2KeyEventKind + wv2EventKeyDown = 0 + wv2EventKeyUp = 1 + wv2EventSystemKeyDown = 2 + wv2EventSystemKeyUp = 3 +End Enum +``` + +| Value | Name | Description | +| ----- | ----------------------- | ------------------------------------- | +| 0 | `wv2EventKeyDown` | Key pressed | +| 1 | `wv2EventKeyUp` | Key released | +| 2 | `wv2EventSystemKeyDown` | System key pressed (like Alt) | +| 3 | `wv2EventSystemKeyUp` | System key released | + +--- + +## wv2WebResourceContext + +Web resource context type enumeration, used in `AddWebResourceRequestedFilter` method. + +```vb +Enum wv2WebResourceContext + wv2All = 0 + wv2Document = 1 + wv2Stylesheet = 2 + wv2Image = 3 + wv2Media = 4 + wv2Font = 5 + wv2Script = 6 + wv2XMLHttpRequest = 7 + wv2Fetch = 8 + wv2TextTrack = 9 + wv2EventSource = 10 + wv2WebSocket = 11 + wv2Manifest = 12 + wv2SignedExchange = 13 + wv2Ping = 14 + wv2CspViolationReport = 15 + wv2Other = 16 +End Enum +``` + +| Value | Name | Description | +| ----- | ----------------------- | ------------------------------------- | +| 0 | `wv2All` | All resource types | +| 1 | `wv2Document` | HTML document | +| 2 | `wv2Stylesheet` | CSS stylesheet | +| 3 | `wv2Image` | Image resources | +| 4 | `wv2Media` | Media resources (audio/video) | +| 5 | `wv2Font` | Font resources | +| 6 | `wv2Script` | JavaScript script | +| 7 | `wv2XMLHttpRequest` | XMLHttpRequest requests | +| 8 | `wv2Fetch` | Fetch API requests | +| 9 | `wv2TextTrack` | Text track | +| 10 | `wv2EventSource` | EventSource (SSE) | +| 11 | `wv2WebSocket` | WebSocket | +| 12 | `wv2Manifest` | Web application manifest | +| 13 | `wv2SignedExchange` | Signed exchange | +| 14 | `wv2Ping` | Ping request | +| 15 | `wv2CspViolationReport` | CSP violation report | +| 16 | `wv2Other` | Other types | + +**Usage Example:** + +```vb +' Intercept all image requests +WebView21.AddWebResourceRequestedFilter("*://*/*.png", wv2Image) +WebView21.AddWebResourceRequestedFilter("*://*/*.jpg", wv2Image) + +' Intercept all XMLHttpRequests +WebView21.AddWebResourceRequestedFilter("*://api.example.com/*", wv2XMLHttpRequest) +``` + +--- + +## wv2ProcessFailedKind + +Process failure type enumeration, used in `ProcessFailed` event. + +```vb +Enum wv2ProcessFailedKind + wv2BrowserProcessExited = 0 + wv2RenderProcessExited = 1 + wv2RenderProcessUnresponsive = 2 + wv2FrameRenderProcessExited = 3 + wv2UtilityProcessExited = 4 + wv2SandboxHelperProcessExited = 5 + wv2GpuProcessExited = 6 + wv2PpapiPluginProcessExited = 7 + wv2PpapiBrokerProcessExited = 8 + wv2UnknownProcessExited = 9 +End Enum +``` + +| Value | Name | Description | +| ----- | ------------------------------- | --------------------------------- | +| 0 | `wv2BrowserProcessExited` | Browser process exited | +| 1 | `wv2RenderProcessExited` | Render process exited | +| 2 | `wv2RenderProcessUnresponsive` | Render process unresponsive | +| 3 | `wv2FrameRenderProcessExited` | Frame render process exited | +| 4 | `wv2UtilityProcessExited` | Utility process exited | +| 5 | `wv2SandboxHelperProcessExited` | Sandbox helper process exited | +| 6 | `wv2GpuProcessExited` | GPU process exited | +| 7 | `wv2PpapiPluginProcessExited` | PPAPI plugin process exited | +| 8 | `wv2PpapiBrokerProcessExited` | PPAPI Broker process exited | +| 9 | `wv2UnknownProcessExited` | Unknown process exited | + +**Usage Example:** + +```vb +Private Sub WebView21_ProcessFailed(ByVal Kind As wv2ProcessFailedKind) + Select Case Kind + Case wv2RenderProcessExited + MsgBox "Render process exited, page may need refresh" + Case wv2RenderProcessUnresponsive + MsgBox "Page unresponsive" + End Select +End Sub +``` + +--- + +## wv2ScriptDialogKind + +Script dialog type enumeration, used in `ScriptDialogOpening` event. + +```vb +Enum wv2ScriptDialogKind + wv2DialogAlert = 0 + wv2DialogConfirm = 1 + wv2DialogPrompt = 2 + wv2DialogBeforeUnload = 3 +End Enum +``` + +| Value | Name | Description | +| ----- | ----------------------- | ------------------------------------------ | +| 0 | `wv2DialogAlert` | Alert dialog (`alert()`) | +| 1 | `wv2DialogConfirm` | Confirm dialog (`confirm()`) | +| 2 | `wv2DialogPrompt` | Prompt dialog (`prompt()`) | +| 3 | `wv2DialogBeforeUnload` | Page leave confirmation dialog | + +**Usage Example:** + +```vb +Private Sub WebView21_ScriptDialogOpening(ByVal ScriptDialogKind As wv2ScriptDialogKind, _ + ByRef Accept As Boolean, ByVal ResultText As String, ByVal URI As String, _ + ByVal Message As String, ByVal DefaultText As String) + + Select Case ScriptDialogKind + Case wv2DialogAlert + MsgBox Message, vbExclamation, "Notification" + Accept = True + Case wv2DialogConfirm + Accept = (MsgBox(Message, vbYesNo + vbQuestion) = vbYes) + Case wv2DialogPrompt + ResultText = InputBox(Message, "Input", DefaultText) + Accept = (ResultText <> "") + End Select +End Sub +``` + +--- + +## wv2HostResourceAccessKind + +Host resource access type enumeration, used in `SetVirtualHostNameToFolderMapping` method. + +```vb +Enum wv2HostResourceAccessKind + wv2ResourceDeny = 0 + wv2ResourceAllow = 1 + wv2ResourceDenyCors = 2 +End Enum +``` + +| Value | Name | Description | +| ----- | --------------------- | ----------------------------------------- | +| 0 | `wv2ResourceDeny` | Deny access | +| 1 | `wv2ResourceAllow` | Allow access | +| 2 | `wv2ResourceDenyCors` | Allow access but deny CORS requests | + +**Usage Example:** + +```vb +' Allow access to local folder +WebView21.SetVirtualHostNameToFolderMapping("app.local", _ + "C:\\MyApp\\Resources", wv2ResourceAllow) + +' Use in HTML +' +``` + +--- + +## wv2PrintOrientation + +Print orientation enumeration, used in `PrintToPdf` method. + +```vb +Enum wv2PrintOrientation + wv2PrintPortrait = 0 + wv2PrintLandscape = 1 +End Enum +``` + +| Value | Name | Description | +| ----- | ------------------- | ---------------- | +| 0 | `wv2PrintPortrait` | Portrait print | +| 1 | `wv2PrintLandscape` | Landscape print | + +**Usage Example:** + +```vb +' Landscape print to PDF +WebView21.PrintToPdf "C:\\output.pdf", wv2PrintLandscape +``` + +--- + +## wv2DefaultDownloadCornerAlign + +Default download dialog corner alignment enumeration. + +```vb +Enum wv2DefaultDownloadCornerAlign + wv2CornerTopLeft = 0 + wv2CornerTopRight = 1 + wv2CornerBottomLeft = 2 + wv2CornerBottomRight = 3 +End Enum +``` + +| Value | Name | Description | +| ----- | ---------------------- | ----------- | +| 0 | `wv2CornerTopLeft` | Top-left | +| 1 | `wv2CornerTopRight` | Top-right | +| 2 | `wv2CornerBottomLeft` | Bottom-left | +| 3 | `wv2CornerBottomRight` | Bottom-right| diff --git a/docs/PackageReference/Webview2/WebView2-Events.md b/docs/PackageReference/Webview2/WebView2-Events.md new file mode 100644 index 0000000..448b759 --- /dev/null +++ b/docs/PackageReference/Webview2/WebView2-Events.md @@ -0,0 +1,659 @@ +--- +title: Events +parent: WebView2 Package +nav_order: 5 +--- + +# WebView2 Events Reference + +The WebView2 control provides rich events to monitor and control web content behavior. + +## Event List + +### Create + +Fired before the WebView2 control is created. Use this event to control `EnvironmentOptions`, such as `UserDataFolder`. + +**Syntax:** + +```vb +Public Event Create() +``` + +**Purpose:** + +- Configure environment options +- Set user data folder +- Initialize control state + +--- + +### Ready + +Fired after the WebView2 control is created and ready. + +**Syntax:** + +```vb +Public Event Ready() +``` + +**Purpose:** + +- Start navigation operations +- Execute initialization code that requires the control to be ready +- Configure subsequent operations + +**Example:** + +```vb +Private Sub WebView21_Ready() + WebView21.Navigate "https://www.example.com" +End Sub +``` + +--- + +### Error + +Captures errors that occur during WebView2 control initialization. + +**Syntax:** + +```vb +Public Event Error(ByVal code As Long, ByVal msg As String) +``` + +**Parameters:** + +- `code` - Error code +- `msg` - Error message description + +**Purpose:** + +- Handle initialization failures +- Display error messages to users +- Log errors + +--- + +### NavigationStarting + +Fired before navigation starts. + +**Syntax:** + +```vb +Public Event NavigationStarting(ByVal Uri As String, _ + ByVal IsUserInitiated As Boolean, _ + ByVal IsRedirected As Boolean, _ + ByVal RequestHeaders As WebView2RequestHeaders, _ + ByRef Cancel As Boolean) +``` + +**Parameters:** + +- `Uri` - Target URI +- `IsUserInitiated` - Whether initiated by user +- `IsRedirected` - Whether it's a redirect +- `RequestHeaders` - Request headers object +- `Cancel` - Set to True to cancel navigation + +**Purpose:** + +- Check or modify request headers +- Cancel specific navigation +- Log navigation history + +**Example:** + +```vb +Private Sub WebView21_NavigationStarting(ByVal Uri As String, ByVal IsUserInitiated As Boolean, _ + ByVal IsRedirected As Boolean, ByVal RequestHeaders As WebView2RequestHeaders, _ + ByRef Cancel As Boolean) + If InStr(Uri, "blocked-site.com") > 0 Then + Cancel = True + End If +End Sub +``` + +--- + +### NavigationComplete + +Fired after calls like `Navigate`, `NavigateCustom`, and `NavigateToString` complete. + +**Syntax:** + +```vb +Public Event NavigationComplete(ByVal IsSuccess As Boolean, ByVal WebErrorStatus As Long) +``` + +**Parameters:** + +- `IsSuccess` - Whether navigation was successful +- `WebErrorStatus` - Web error status code + +**Purpose:** + +- Update UI state +- Handle navigation errors +- Begin page content processing + +--- + +### SourceChanged + +Fired when the `DocumentURL` property updates, typically after page navigation. + +**Syntax:** + +```vb +Public Event SourceChanged(ByVal IsNewDocument As Boolean) +``` + +**Parameters:** + +- `IsNewDocument` - Whether it's a new document + +**Purpose:** + +- Sync URL bar +- Update navigation history +- Detect page changes + +**Example:** + +```vb +Private Sub WebView21_SourceChanged(ByVal IsNewDocument As Boolean) + txtURL.Text = WebView21.DocumentURL +End Sub +``` + +--- + +### DocumentTitleChanged + +Fired when the `DocumentTitle` property updates, typically after page navigation. + +**Syntax:** + +```vb +Public Event DocumentTitleChanged() +``` + +**Purpose:** + +- Update window title +- Display page title +- Log page visits + +--- + +### PermissionRequested + +Fired when a webpage needs task authorization, such as reading from the clipboard or viewing live camera feed. + +**Syntax:** + +```vb +Public Event PermissionRequested(ByVal IsUserInitiated As Boolean, _ + ByRef State As wv2PermissionState, _ + ByVal Uri As String, _ + ByVal PermissionKind As wv2PermissionKind) +``` + +**Parameters:** + +- `IsUserInitiated` - Whether initiated by user +- `State` - Permission state (modifiable to grant/deny permission) +- `Uri` - URI requesting permission +- `PermissionKind` - Permission type + +**Purpose:** + +- Control camera and microphone access permissions +- Control clipboard access +- Implement custom permission prompts + +--- + +### AcceleratorKeyPressed + +Fired when an accelerator key is pressed. + +**Syntax:** + +```vb +Public Event AcceleratorKeyPressed(ByRef KeyState As wv2KeyEventKind, _ + ByVal IsExtendedKey As Boolean, _ + ByVal WasKeyDown As Boolean, _ + ByVal IsKeyReleased As Boolean, _ + ByVal IsMenuKeyDown As Boolean, _ + ByVal RepeatCount As Long, _ + ByVal ScanCode As Long, _ + ByRef IsHandled As Boolean) +``` + +**Parameters:** + +- `KeyState` - Key event type +- `IsExtendedKey` - Whether it's an extended key +- `WasKeyDown` - Whether it's a key down +- `IsKeyReleased` - Whether it's a key release +- `IsMenuKeyDown` - Whether menu key is down +- `RepeatCount` - Repeat count +- `ScanCode` - Scan code +- `IsHandled` - Set to True to indicate handled + +**Purpose:** + +- Intercept keyboard shortcuts +- Implement custom keyboard handling +- Prevent default behavior + +--- + +### WebResourceRequested + +Fired when an HTTP request matching a URI set via `AddWebResourceRequestedFilter` is made. + +**Syntax:** + +```vb +Public Event WebResourceRequested(ByVal Request As WebView2Request, _ + ByVal Response As WebView2Response) +``` + +**Parameters:** + +- `Request` - Request object +- `Response` - Response object + +**Purpose:** + +- Intercept and modify requests +- Provide custom responses +- Implement resource caching +- Block specific requests + +--- + +### ProcessFailed + +Fired when an external EXE process used by WebView2 fails (e.g., rendering or JavaScript external process). + +**Syntax:** + +```vb +Public Event ProcessFailed(ByVal Kind As wv2ProcessFailedKind) +``` + +**Parameters:** + +- `Kind` - Process failure type + +**Purpose:** + +- Handle crash recovery +- Log error information +- Notify users + +--- + +### ScriptDialogOpening + +Fired when `AreDefaultScriptDialogsEnabled` is set to False, allowing you to present custom dialogs. + +**Syntax:** + +```vb +Public Event ScriptDialogOpening(ByVal ScriptDialogKind As wv2ScriptDialogKind, _ + ByRef Accept As Boolean, _ + ByVal ResultText As String, _ + ByVal URI As String, _ + ByVal Message As String, _ + ByVal DefaultText As String) +``` + +**Parameters:** + +- `ScriptDialogKind` - Dialog type +- `Accept` - Set to True to accept (for confirmation dialogs) +- `ResultText` - Result text +- `URI` - URI making the request +- `Message` - Dialog message +- `DefaultText` - Default text + +**Purpose:** + +- Implement custom alert dialogs +- Implement custom prompt dialogs +- Implement custom confirm dialogs + +**Example:** + +```vb +Private Sub WebView21_ScriptDialogOpening(ScriptDialogKind As wv2ScriptDialogKind, _ + ByRef Accept As Boolean, ResultText As String, _ + URI As String, Message As String, DefaultText As String) + If ScriptDialogKind = wv2ScriptDialogKind.wv2Alert Then + MsgBox Message, vbInformation, "Alert" + End If +End Sub +``` + +--- + +### UserContextMenu + +Fired when the user right-clicks within the WebView control. Set `AreDefaultContextMenusEnabled` to False and use this event to implement your own context menu. + +**Syntax:** + +```vb +Public Event UserContextMenu(X As Single, Y As Single) +``` + +**Parameters:** + +- `X` - Mouse X coordinate +- `Y` - Mouse Y coordinate + +**Purpose:** + +- Implement custom right-click menu +- Disable default menu + +--- + +### DOMContentLoaded + +Fired when the DOM document is fully loaded and accessible from the JavaScript side. + +**Syntax:** + +```vb +Public Event DOMContentLoaded() +``` + +**Purpose:** + +- Execute page initialization scripts +- Manipulate DOM elements +- Check page state + +--- + +### SuspendCompleted + +Fired after a successful `Suspend` request. + +**Syntax:** + +```vb +Public Event SuspendCompleted() +``` + +**Purpose:** + +- Confirm suspension completion +- Update UI state + +--- + +### SuspendFailed + +Fired after a failed `Suspend` request. + +**Syntax:** + +```vb +Public Event SuspendFailed() +``` + +**Purpose:** + +- Handle suspension failure +- Retry or notify user + +--- + +### DownloadStarting + +Fired when the user clicks content that will be downloaded, allowing you to override the download path or cancel the operation. + +**Syntax:** + +```vb +Public Event DownloadStarting(ByRef ResultFilePath As String, _ + ByRef Cancel As Boolean, _ + ByRef Handled As Boolean) +``` + +**Parameters:** + +- `ResultFilePath` - Result file path (modifiable) +- `Cancel` - Set to True to cancel download +- `Handled` - Set to True to indicate handled + +**Purpose:** + +- Change download location +- Cancel unwanted downloads +- Implement custom download management + +**Example:** + +```vb +Private Sub WebView21_DownloadStarting(ByRef ResultFilePath As String, _ + ByRef Cancel As Boolean, _ + ByRef Handled As Boolean) + ResultFilePath = "C:\Downloads\" & Mid(ResultFilePath, InStrRev(ResultFilePath, "\") + 1) +End Sub +``` + +--- + +### PrintToPdfCompleted + +Fired after a successful `PrintToPdf` request. + +**Syntax:** + +```vb +Public Event PrintToPdfCompleted() +``` + +**Purpose:** + +- Notify PDF print completion +- Update UI state + +--- + +### PrintToPdfFailed + +Fired after a failed `PrintToPdf` request. + +**Syntax:** + +```vb +Public Event PrintToPdfFailed() +``` + +**Purpose:** + +- Handle print failure +- Notify user + +--- + +### NewWindowRequested + +Fired when a new web page window is about to be opened. Set `IsHandled` to True if you have handled the request (thus suppressing the default behavior of opening a new Edge window). + +**Syntax:** + +```vb +Public Event NewWindowRequested(ByVal IsUserInitiated As Boolean, _ + ByRef IsHandled As Boolean, _ + ByVal Uri As String, _ + ByVal HasPosition As Long, _ + ByVal HasSize As Long, _ + ByVal Left As Long, _ + ByVal Top As Long, _ + ByVal Width As Long, _ + ByVal Height As Long, _ + ByVal ShouldDisplayMenuBar As Long, _ + ByVal ShouldDisplayStatus As Long, _ + ByVal ShouldDisplayToolbar As Long, _ + ByVal ShouldDisplayScrollBars As Long) +``` + +**Parameters:** + +- `IsUserInitiated` - Whether initiated by user +- `IsHandled` - Set to True to indicate handled +- `Uri` - New window URI +- `HasPosition` - Whether position is specified +- `HasSize` - Whether size is specified +- `Left` - Left margin +- `Top` - Top margin +- `Width` - Width +- `Height` - Height +- `ShouldDisplayMenuBar` - Whether to display menu bar +- `ShouldDisplayStatus` - Whether to display status bar +- `ShouldDisplayToolbar` - Whether to display toolbar +- `ShouldDisplayScrollBars` - Whether to display scroll bars + +**Purpose:** + +- Open new window within application +- Block popups +- Control window properties + +--- + +### JsAsyncResult + +Fired in response to the `JsRunAsync` function, providing the JavaScript result. + +**Syntax:** + +```vb +Public Event JsAsyncResult(ByVal Result As Variant, _ + Token As LongLong, _ + ErrString As String) +``` + +**Parameters:** + +- `Result` - JavaScript execution result +- `Token` - Token used to identify the request +- `ErrString` - Error string (if any) + +**Purpose:** + +- Handle asynchronous JavaScript execution results +- Match requests by token + +--- + +### JsMessage + +Fired when the JavaScript side calls `window.chrome.webview.postMessage(...)`. `IsWebMessageEnabled` must be True. + +**Syntax:** + +```vb +Public Event JsMessage(ByVal Message As Variant) +``` + +**Parameters:** + +- `Message` - Message from JavaScript + +**Purpose:** + +- Receive messages from web pages +- Implement JavaScript to native code communication + +**Example:** + +JavaScript side: + +```javascript +// Send simple string +window.chrome.webview.postMessage("Hello from JavaScript"); + +// Send object (automatically converted to JSON) +window.chrome.webview.postMessage({ + type: "alert", + message: "Hello", + timestamp: Date.now(), +}); +``` + +twinBASIC side: + +```vb +' Receive string +Private Sub WebView21_JsMessage(ByVal Message As Variant) + If VarType(Message) = vbString Then + Debug.Print "Received message: " & Message + End If +End Sub + +' Receive object (JavaScript objects are converted to Dictionary) +Private Sub WebView21_JsMessage(ByVal Message As Variant) + If VarType(Message) = vbObject Then + Dim msg As Object + Set msg = Message + + ' JavaScript object properties are automatically converted to Dictionary keys + If msg.Exists("type") And msg("type") = "alert" Then + MsgBox msg("message") + End If + End If +End Sub + +' Use Scripting.Dictionary for easier handling +Private Sub WebView21_JsMessage(ByVal Message As Variant) + If VarType(Message) = vbObject Then + Dim msg As Scripting.Dictionary + Set msg = Message + + Select Case msg("type") + Case "alert" + MsgBox msg("message") + Case "notification" + Debug.Print "Notification: " & msg("text") + End Select + End If +End Sub +``` + +--- + +### DevToolsProtocolResponse + +Fired in response to `CallDevToolsProtocolMethod`. + +**Syntax:** + +```vb +Public Event DevToolsProtocolResponse(ByVal CustomEventId As Variant, _ + ByVal JsonResponse As String) +``` + +**Parameters:** + +- `CustomEventId` - Custom event ID +- `JsonResponse` - JSON formatted response + +**Purpose:** + +- Receive Developer Tools Protocol response +- Implement advanced debugging features + diff --git a/docs/PackageReference/Webview2/WebView2-Methods.md b/docs/PackageReference/Webview2/WebView2-Methods.md new file mode 100644 index 0000000..2a054f8 --- /dev/null +++ b/docs/PackageReference/Webview2/WebView2-Methods.md @@ -0,0 +1,888 @@ +--- +title: Methods +parent: WebView2 Package +nav_order: 7 +--- + +# WebView2 Methods Reference + +The WebView2 control provides rich methods to control navigation, execute JavaScript, manage resources, etc. + +## Method List + +### MoveFocus + +Sets focus to the WebView control. + +**Syntax:** + +```vb +Public Sub MoveFocus() +``` + +**Example:** + +```vb +WebView21.MoveFocus +``` + +--- + +### Navigate + +Navigates to the requested URI. URIs need a protocol prefix, such as http://. Triggers `NavigationStarting` and `NavigationComplete` events. + +**Syntax:** + +```vb +Public Sub Navigate(ByVal uri As String) +``` + +**Parameters:** + +- `uri` - Target URI + +**Example:** + +```vb +WebView21.Navigate "https://www.example.com" +' Protocol prefix not required, https:// is added automatically +WebView21.Navigate "www.example.com" +``` + +--- + +### NavigateCustom + +Navigates to the requested URI using the specified HTTP method (e.g., GET/POST), optional HTTP headers (vbCrLf separated), and optional POST data. URIs need a protocol prefix, such as http://. Triggers `NavigationStarting` and `NavigationComplete` events. + +**Syntax:** + +```vb +Public Sub NavigateCustom(ByVal uri As String, _ + method As String, _ + Optional headers As String, _ + Optional postData As Variant, _ + Optional postDataAsUTF8 As Boolean = True) +``` + +**Parameters:** + +- `uri` - Target URI +- `method` - HTTP method (such as "GET", "POST") +- `headers` - Optional, HTTP headers (vbCrLf separated) +- `postData` - Optional, POST data +- `postDataAsUTF8` - Optional, whether to encode postData as UTF-8 (default True) + +**Note:** Use `SupportsNavigateCustomFeatures` to check if this feature is supported. + +**Example:** + +```vb +' POST request +Dim postData As String +postData = "username=admin&password=123456" +WebView21.NavigateCustom "https://api.example.com/login", "POST", _ + "Content-Type: application/x-www-form-urlencoded", _ + postData + +' GET request with custom headers +WebView21.NavigateCustom "https://api.example.com/data", "GET", _ + "Authorization: Bearer token123" +``` + +--- + +### NavigateToString + +Navigates to the requested HTML string content. Triggers `NavigationStarted` and `NavigationComplete` events. + +**Syntax:** + +```vb +Public Sub NavigateToString(ByVal htmlContent As String) +``` + +**Parameters:** + +- `htmlContent` - HTML content string + +**Example:** + +```vb +Dim html As String +html = "

Hello World

" +WebView21.NavigateToString html +``` + +--- + +### GoBack + +Navigates to the previous URL in the browser navigation history. + +**Syntax:** + +```vb +Public Sub GoBack() +``` + +**Example:** + +```vb +If WebView21.CanGoBack Then + WebView21.GoBack +End If +``` + +--- + +### GoForward + +Navigates to the next URL in the browser navigation history. + +**Syntax:** + +```vb +Public Sub GoForward() +``` + +**Example:** + +```vb +If WebView21.CanGoForward Then + WebView21.GoForward +End If +``` + +--- + +### Reload + +Reloads the current URL, equivalent to the F5 key. + +**Syntax:** + +```vb +Public Sub Reload() +``` + +**Example:** + +```vb +WebView21.Reload +``` + +--- + +### AddObject + +Makes a COM object accessible from the JavaScript side via the `chrome.webview.hostObjects.ObjName` JavaScript syntax. + +**Syntax:** + +```vb +Public Sub AddObject(ByVal ObjName As String, ByVal Object As Object, ByVal UseDeferredInvoke As Boolean = False) +``` + +**Parameters:** + +- `ObjName` - Object name to use in JavaScript +- `Object` - COM object to expose +- `UseDeferredInvoke` - Optional, whether to use deferred invocation (default False) + +**UseDeferredInvoke Description:** + +| Value | Description | +| ------- | ------------------------------------------------------------------------------------------------------ | +| `False` | Direct invocation, can return values to JavaScript, but may cause reentrancy issues | +| `True` | Deferred invocation, avoids reentrancy issues, returns values to JavaScript via Promise asynchronously | + +See [Deferred Callback Mechanism](./DeferredCallback.md#addobject-deferred-invocation) for detailed comparison and use cases of both modes. + +**Example:** + +```vb +' Add object (default using direct invocation mode) +Set myObject = New MyClass +WebView21.AddObject "MyObject", myObject + +' Add deferred invocation mode object (avoids reentrancy issues) +Set dataProcessor = New DataProcessor +WebView21.AddObject "Processor", dataProcessor, True +``` + +**JavaScript Side Call Example:** + +```javascript +// Direct invocation mode (UseDeferredInvoke = False) +const result = chrome.webview.hostObjects.MyObject.GetValue(); +console.log(result); // Directly get return value + +// Deferred invocation mode (UseDeferredInvoke = True) +chrome.webview.hostObjects.Processor.ProcessData("data").then( + function (result) { + console.log("Processing result:", result); // Get return value via Promise + }, +); + +// Or use async/await +async function processData() { + const result = await chrome.webview.hostObjects.Processor.ProcessData("data"); + console.log(result); +} +``` + +--- + +### RemoveObject + +Removes a COM object previously exposed via `AddObject`. + +**Syntax:** + +```vb +Public Sub RemoveObject(ByVal ObjName As String) +``` + +**Parameters:** + +- `ObjName` - Object name to remove + +**Example:** + +```vb +WebView21.RemoveObject "MyObject" +``` + +--- + +### AddScriptToExecuteOnDocumentCreated + +Sets JavaScript code to inject into each subsequent navigated webpage. Only takes effect on the next URL navigation. + +**Syntax:** + +```vb +Public Sub AddScriptToExecuteOnDocumentCreated(ByVal jsCode As String) +``` + +**Parameters:** + +- `jsCode` - JavaScript code to inject + +**Example:** + +```vb +' Inject custom script +WebView21.AddScriptToExecuteOnDocumentCreated _ + "window.addEventListener('load', function() {" & vbCrLf & _ + " console.log('Page loaded!');" & vbCrLf & _ + "});" +``` + +--- + +### AddWebResourceRequestedFilter + +Sets a URL filter that will trigger the `WebResourceRequested` event. Use `*` and `?` for wildcard matching. + +**Syntax:** + +```vb +Public Sub AddWebResourceRequestedFilter(ByVal sFilter As String, ByVal FilterContext As wv2WebResourceContext) +``` + +**Parameters:** + +- `sFilter` - URL filter pattern (supports wildcards) +- `FilterContext` - Web resource context + +**Example:** + +```vb +' Intercept all image requests +WebView21.AddWebResourceRequestedFilter "*.jpg", wv2WebResourceContext.wv2Image + +' Intercept all requests for a specific domain +WebView21.AddWebResourceRequestedFilter "https://api.example.com/*", wv2WebResourceContext.wv2All +``` + +--- + +### RemoveWebResourceRequestedFilter + +Removes a URL filter previously added via `AddWebResourceRequestedFilter`. + +**Syntax:** + +```vb +Public Sub RemoveWebResourceRequestedFilter(ByVal sFilter As String, ByVal FilterContext As wv2WebResourceContext) +``` + +**Parameters:** + +- `sFilter` - URL filter pattern +- `FilterContext` - Web resource context + +**Example:** + +```vb +WebView21.RemoveWebResourceRequestedFilter "*.jpg", wv2WebResourceContext.wv2Image +``` + +--- + +### OpenDevToolsWindow + +Opens the Developer Tools window. + +**Syntax:** + +```vb +Public Sub OpenDevToolsWindow() +``` + +**Example:** + +```vb +WebView21.OpenDevToolsWindow +``` + +--- + +### CallDevToolsProtocolMethod + +Sends a protocol message to the Developer Tools window. If `CustomEventId` is provided, the `DevToolsProtocolResponse` event will be triggered with the result. + +**Syntax:** + +```vb +Public Sub CallDevToolsProtocolMethod(ByVal MethodName As String, _ + ByVal ParamsAsJson As String, _ + Optional CustomEventId As Variant) +``` + +**Parameters:** + +- `MethodName` - Method name +- `ParamsAsJson` - JSON formatted parameters +- `CustomEventId` - Optional, custom event ID + +**Example:** + +```vb +' Disable script execution +WebView21.CallDevToolsProtocolMethod "Emulation.setScriptExecutionDisabled", "{""value"":true}" + +' With custom ID, receive response +WebView21.CallDevToolsProtocolMethod "Runtime.evaluate", "{""expression"":'document.title'}", "MyEventId" + +' Handle in event: +Private Sub WebView21_DevToolsProtocolResponse(ByVal CustomEventId As Variant, ByVal JsonResponse As String) + If CustomEventId = "MyEventId" Then + Debug.Print JsonResponse + End If +End Sub +``` + +--- + +### ExecuteScript + +Triggers execution of the provided JavaScript code. Does not wait for completion and provides no result. + +**Syntax:** + +```vb +Public Sub ExecuteScript(ByVal jsCode As String) +``` + +**Parameters:** + +- `jsCode` - JavaScript code + +**Example:** + +```vb +WebView21.ExecuteScript "alert('Hello from WebView2!')" +``` + +--- + +### JsRun + +Executes the provided JavaScript function with its parameters, waits for completion, and returns the result. + +**Syntax:** + +```vb +Public Function JsRun(ByVal FuncName As String, ParamArray args() As Variant) As Variant +``` + +**Parameters:** + +- `FuncName` - JavaScript function name +- `args` - Parameter array + +**Return Value:** Return value of the JavaScript function + +**Example:** + +```vb +' Call simple function +Dim result As Variant +result = WebView21.JsRun("Math.max", 10, 20, 30) +Debug.Print result ' Output: 30 + +' Call custom function +WebView21.ExecuteScript "function add(a, b) { return a + b; }" +result = WebView21.JsRun("add", 5, 3) +Debug.Print result ' Output: 8 + +' Get page property +result = WebView21.JsProp("document.title") +Debug.Print result ' Output page title +``` + +--- + +### JsRunAsync + +Triggers asynchronous execution of the given JavaScript function with its parameters. Returns a token for identification. When the result arrives, the `JsAsyncResult` event is triggered (providing the token as one of its parameters). + +**Syntax:** + +```vb +Public Function JsRunAsync(ByVal FuncName As String, ParamArray args() As Variant) As LongLong +``` + +**Parameters:** + +- `FuncName` - JavaScript function name +- `args` - Parameter array + +**Return Value:** Token used to identify the request + +**Example:** + +```vb +Dim token As LongLong +token = WebView21.JsRunAsync("fetchData", "https://api.example.com/data") + +Private Sub WebView21_JsAsyncResult(ByVal Result As Variant, Token As LongLong, ErrString As String) + If Token = token Then + Debug.Print "Result: " & Result + End If +End Sub +``` + +--- + +### JsProp + +Executes the given JavaScript code (e.g., 'document.url'), waits for completion, and returns the result. + +**Syntax:** + +```vb +Public Function JsProp(ByVal PropName As String) As Variant +``` + +**Parameters:** + +- `PropName` - JavaScript property or expression + +**Return Value:** Property value or expression result + +**Example:** + +```vb +Dim url As String +url = WebView21.JsProp("document.URL") +Debug.Print url + +Dim title As String +title = WebView21.JsProp("document.title") +Debug.Print title + +Dim scrollPos As Long +scrollPos = WebView21.JsProp("window.scrollY") +Debug.Print scrollPos +``` + +--- + +### PostWebMessage + +Sends a message to the JavaScript side, which can be received via `window.chrome.webview.addEventListener('message', handler)`. Requires `IsWebMessageEnabled` to be set to True. + +**Syntax:** + +```vb +Public Sub PostWebMessage(Message As Variant) +``` + +**Parameters:** + +- `Message` - Message to send (can be a string or other type, non-string types are automatically converted to JSON) + +**Description:** + +- If `Message` is a string type, use `PostWebMessageAsString` to send the raw string +- If `Message` is another type (including objects), use `PostWebMessageAsJson` to automatically convert to JSON + +**Example:** + +```vb +' Send string +WebView21.PostWebMessage "Hello from VB6" + +' Send object (automatically converted to JSON) +Dim dict As Object +Set dict = CreateObject("Scripting.Dictionary") +dict("type") = "notification" +dict("message") = "Data updated" +dict("timestamp") = CLng(Now) +WebView21.PostWebMessage dict + +' JavaScript side receive: +// window.chrome.webview.addEventListener('message', (event) => { +// console.log(event.data); +// // String: "Hello from VB6" +// // Object: {type: "notification", message: "Data updated", timestamp: ...} +// }); + +// Or use async/await to receive messages +// window.chrome.webview.addEventListener('message', async (event) => { +// const data = event.data; +// if (typeof data === 'string') { +// console.log('String:', data); +// } else { +// console.log('Object:', data.type, data.message); +// } +// }); +``` + +--- + +### PostWebMessageJSON + +Sends raw JSON value to the JavaScript side, which can be received via `window.chrome.webview.addEventListener('message', handler)`. Requires `IsWebMessageEnabled` to be set to True. + +**Syntax:** + +```vb +Public Sub PostWebMessageJSON(jsonString As String) +``` + +**Parameters:** + +- `jsonString` - JSON formatted string + +**Example:** + +```vb +WebView21.PostWebMessageJSON "{""type"":""alert"",""message"":""Hello""}" +``` + +--- + +### Suspend + +Suspends WebView2 processing/rendering. Useful for creating tabs. Use `SupportsSuspendResumeFeatures` to check if this feature is supported. + +**Syntax:** + +```vb +Public Sub Suspend() +``` + +**Example:** + +```vb +If WebView21.SupportsSuspendResumeFeatures Then + WebView21.Suspend +End If + +Private Sub WebView21_SuspendCompleted() + Debug.Print "WebView suspended successfully" +End Sub +``` + +--- + +### Resume + +Resumes WebView2 processing/rendering after a previous `Suspend` call. Use `SupportsSuspendResumeFeatures` to check if this feature is supported. + +**Syntax:** + +```vb +Public Sub Resume() +``` + +**Example:** + +```vb +If WebView21.SupportsSuspendResumeFeatures Then + WebView21.Resume +End If +``` + +--- + +### SetVirtualHostNameToFolderMapping + +Creates a virtual mapping of the specified hostname to a local folder. Use `SupportsFolderMappingFeatures` to check if this feature is supported. + +**Note:** Due to a WebView2 bug, this may cause a 2-second delay in name resolution if you're not careful with the hostname selection. See https://github.com/MicrosoftEdge/WebView2Feedback/issues/2381 + +**Syntax:** + +```vb +Public Sub SetVirtualHostNameToFolderMapping(ByVal hostName As String, _ + ByVal folderPath As String, _ + ByVal accessKind As wv2HostResourceAccessKind = wv2HostResourceAccessKind.wv2ResourceAllow) +``` + +**Parameters:** + +- `hostName` - Virtual hostname +- `folderPath` - Local folder path +- `accessKind` - Access type (default wv2ResourceAllow) + +**Example:** + +```vb +' Map local folder as virtual domain +WebView21.SetVirtualHostNameToFolderMapping "app.local", "C:\MyApp\wwwroot" + +' Now can access local files +WebView21.Navigate "https://app.local/index.html" +``` + +--- + +### ClearVirtualHostNameToFolderMapping + +Removes the virtual mapping of the specified hostname previously set via `SetVirtualHostNameToFolderMapping`. Use `SupportsFolderMappingFeatures` to check if this feature is supported. + +**Syntax:** + +```vb +Public Sub ClearVirtualHostNameToFolderMapping(ByVal hostName As String) +``` + +**Parameters:** + +- `hostName` - Hostname to clear + +**Example:** + +```vb +WebView21.ClearVirtualHostNameToFolderMapping "app.local" +``` + +--- + +### PrintToPdf + +Saves the current document as a PDF file. Use `SupportsPdfFeatures` to check if this feature is supported. + +**Syntax:** + +```vb +Public Sub PrintToPdf(ByVal outputPath As String, _ + Optional ByVal Orientation As wv2PrintOrientation = wv2PrintOrientation.wv2PrintPortrait, _ + Optional ByVal ScaleFactor As Variant, _ + Optional PageWidth As Variant, _ + Optional PageHeight As Variant, _ + Optional ByVal MarginTop As Variant, _ + Optional ByVal MarginBottom As Variant, _ + Optional ByVal MarginLeft As Variant, _ + Optional ByVal MarginRight As Variant, _ + Optional ByVal ShouldPrintBackgrounds As Boolean = False, _ + Optional ByVal ShouldPrintSelectionOnly As Boolean = False, _ + Optional ByVal ShouldPrintHeaderAndFooter As Boolean = True, _ + Optional ByVal HeaderTitle As Variant, _ + Optional ByVal FooterUri As Variant) +``` + +**Parameters:** + +- `outputPath` - Output PDF file path +- `Orientation` - Optional, page orientation (default portrait) +- `ScaleFactor` - Optional, scale factor +- `PageWidth` - Optional, page width +- `PageHeight` - Optional, page height +- `MarginTop` - Optional, top margin +- `MarginBottom` - Optional, bottom margin +- `MarginLeft` - Optional, left margin +- `MarginRight` - Optional, right margin +- `ShouldPrintBackgrounds` - Optional, whether to print backgrounds (default False) +- `ShouldPrintSelectionOnly` - Optional, whether to print only selected content (default False) +- `ShouldPrintHeaderAndFooter` - Optional, whether to print header and footer (default True) +- `HeaderTitle` - Optional, header title +- `FooterUri` - Optional, footer URI + +**Example:** + +```vb +' Basic print +WebView21.PrintToPdf "C:\output.pdf" + +' Print landscape with backgrounds +WebView21.PrintToPdf "C:\output.pdf", wv2PrintOrientation.wv2PrintLandscape, , , , , , , , True + +' Full configuration +WebView21.PrintToPdf "C:\output.pdf", _ + wv2PrintOrientation.wv2PrintPortrait, _ + 1.0, _ + 210, _ + 297, _ + 10, _ + 10, _ + 10, _ + 10, _ + True, _ + False, _ + True, _ + "My Document", _ + "https://www.example.com" + +Private Sub WebView21_PrintToPdfCompleted() + MsgBox "PDF saved successfully!" +End Sub +``` + +--- + +### OpenDefaultDownloadDialog + +Opens the built-in download manager dialog. Use `SupportsDownloadDialogFeatures` to check if this feature is supported. + +**Syntax:** + +```vb +Public Sub OpenDefaultDownloadDialog() +``` + +**Example:** + +```vb +WebView21.OpenDefaultDownloadDialog +``` + +--- + +### CloseDefaultDownloadDialog + +Closes the built-in download manager dialog. Use `SupportsDownloadDialogFeatures` to check if this feature is supported. + +**Syntax:** + +```vb +Public Sub CloseDefaultDownloadDialog() +``` + +**Example:** + +```vb +WebView21.CloseDefaultDownloadDialog +``` + +--- + +### OpenTaskManagerWindow + +Opens the built-in task manager dialog. Use `SupportsTaskManagerFeatures` to check if this feature is supported. + +**Syntax:** + +```vb +Public Sub OpenTaskManagerWindow() +``` + +**Example:** + +```vb +WebView21.OpenTaskManagerWindow +``` + +--- + +## Usage Examples + +### Complete Navigation Example + +```vb +Private Sub cmdGo_Click() + WebView21.Navigate txtURL.Text +End Sub + +Private Sub cmdBack_Click() + If WebView21.CanGoBack Then + WebView21.GoBack + End If +End Sub + +Private Sub cmdForward_Click() + If WebView21.CanGoForward Then + WebView21.GoForward + End If +End Sub + +Private Sub cmdReload_Click() + WebView21.Reload +End Sub +``` + +### JavaScript Interaction Example + +```vb +' Synchronous call +Dim title As String +title = WebView21.JsProp("document.title") +Me.Caption = title + +' Call function +Dim result As Variant +result = WebView21.JsRun("parseInt", "12345") +Debug.Print result + +' Asynchronous call +Dim token As LongLong +token = WebView21.JsRunAsync("fetchData", "api/data") +``` + +### Download Management Example + +```vb +Private Sub WebView21_DownloadStarting(ByRef ResultFilePath As String, _ + ByRef Cancel As Boolean, _ + ByRef Handled As Boolean) + ' Change download location + ResultFilePath = "C:\Downloads\" & Mid(ResultFilePath, InStrRev(ResultFilePath, "\") + 1) + Handled = True +End Sub + +Private Sub cmdOpenDownloads_Click() + WebView21.OpenDefaultDownloadDialog +End Sub +``` + +### PDF Export Example + +```vb +Private Sub cmdExportPDF_Click() + If WebView21.SupportsPdfFeatures Then + Dim outputPath As String + outputPath = "C:\Documents\" & WebView21.DocumentTitle & ".pdf" + WebView21.PrintToPdf outputPath, , , , , , , , , True + Else + MsgBox "PDF export not supported" + End If +End Sub +``` + diff --git a/docs/PackageReference/Webview2/WebView2-Properties.md b/docs/PackageReference/Webview2/WebView2-Properties.md new file mode 100644 index 0000000..c1e467f --- /dev/null +++ b/docs/PackageReference/Webview2/WebView2-Properties.md @@ -0,0 +1,666 @@ +--- +title: Properties +parent: WebView2 Package +nav_order: 6 +--- + +# WebView2 Properties Reference + +The WebView2 control provides rich properties to control its behavior and state. + +## Property List + +### DocumentURL + +Sets the URL to open. URIs need a protocol prefix, such as http://. For example: https://www.google.com + +**Type:** String (Read-only) + +**Example:** + +```vb +WebView21.Navigate "https://www.example.com" +Debug.Print WebView21.DocumentURL +``` + +--- + +### DocumentTitle + +Returns the current document title provided by HTML content. + +**Type:** String (Read-only) + +**Example:** + +```vb +Me.Caption = WebView21.DocumentTitle +``` + +--- + +### ZoomFactor + +Sets or gets the overall zoom factor. For example, a value of 1.5 represents a 50% zoom. + +**Type:** Double + +**Example:** + +```vb +WebView21.ZoomFactor = 1.5 ' Zoom in 50% +Debug.Print WebView21.ZoomFactor +``` + +--- + +### BrowserProcessId + +Gets the ProcessID of the external browser EXE process. + +**Type:** Long (Read-only) + +**Example:** + +```vb +Debug.Print "Browser Process ID: " & WebView21.BrowserProcessId +``` + +--- + +### CanGoBack + +Determines if there is backward navigation history. + +**Type:** Boolean (Read-only) + +**Example:** + +```vb +If WebView21.CanGoBack Then + WebView21.GoBack +End If +``` + +--- + +### CanGoForward + +Determines if there is forward navigation history. + +**Type:** Boolean (Read-only) + +**Example:** + +```vb +If WebView21.CanGoForward Then + WebView21.GoForward +End If +``` + +--- + +### hWnd + +Returns the container window handle. + +**Type:** LongPtr (Read-only) + +**Example:** + +```vb +Debug.Print "Window Handle: 0x" & Hex(WebView21.hWnd) +``` + +--- + +### IsScriptEnabled + +Controls whether JavaScript is enabled within the webview. + +**Type:** Boolean (Read/Write) + +**Default Value:** True + +**Example:** + +```vb +WebView21.IsScriptEnabled = False ' Disable JavaScript +``` + +--- + +### IsWebMessageEnabled + +Controls whether PostWebMessage functionality is enabled. + +**Type:** Boolean (Read/Write) + +**Default Value:** True + +**Example:** + +```vb +WebView21.IsWebMessageEnabled = True +``` + +--- + +### AreDefaultScriptDialogsEnabled + +Controls whether default script dialogs are enabled (such as JavaScript alert() function). Set to False and listen to `ScriptDialogOpening` event to implement your own dialogs. + +**Type:** Boolean (Read/Write) + +**Default Value:** True + +**Example:** + +```vb +WebView21.AreDefaultScriptDialogsEnabled = False +``` + +--- + +### IsStatusBarEnabled + +Controls whether the status bar is enabled. + +**Type:** Boolean (Read/Write) + +**Default Value:** True + +**Example:** + +```vb +WebView21.IsStatusBarEnabled = False +``` + +--- + +### AreDevToolsEnabled + +Controls whether users are allowed to open DevTools through context menu or accelerator keys (does not affect `OpenDevToolsWindow` function). + +**Type:** Boolean (Read/Write) + +**Default Value:** True + +**Example:** + +```vb +WebView21.AreDevToolsEnabled = False +``` + +--- + +### AreDefaultContextMenusEnabled + +Controls whether the default Edge context menu is enabled. Set to False and listen to `UserContextMenu` event to use your own. + +**Type:** Boolean (Read/Write) + +**Default Value:** True + +**Example:** + +```vb +WebView21.AreDefaultContextMenusEnabled = False +``` + +--- + +### AreHostObjectsAllowed + +Controls whether `AddObject` functionality can be used to share host COM objects with the JavaScript engine. + +**Type:** Boolean (Read/Write) + +**Default Value:** True + +**Example:** + +```vb +WebView21.AreHostObjectsAllowed = True +``` + +--- + +### IsZoomControlEnabled + +Controls whether users can change the zoom factor using Ctrl++/Ctrl+-/Ctrl+mouse wheel. + +**Type:** Boolean (Read/Write) + +**Default Value:** True + +**Example:** + +```vb +WebView21.IsZoomControlEnabled = False +``` + +--- + +### IsBuiltInErrorPageEnabled + +Controls whether the built-in error page is enabled (such as 404 navigation errors). + +**Type:** Boolean (Read/Write) + +**Default Value:** True + +**Example:** + +```vb +WebView21.IsBuiltInErrorPageEnabled = False +``` + +--- + +### UserAgent + +Sets the UserAgent string to be used in HTTP request headers. + +**Type:** String (Read/Write) + +**Example:** + +```vb +WebView21.UserAgent = "MyApp/1.0" +``` + +**Note:** Use `SupportsUserAgentFeatures` to check if this feature is supported. + +--- + +### AreBrowserAcceleratorKeysEnabled + +Controls whether all default accelerator keys are enabled. For example, F5 to reload. + +**Type:** Boolean (Read/Write) + +**Default Value:** True + +**Example:** + +```vb +WebView21.AreBrowserAcceleratorKeysEnabled = False +``` + +**Note:** Use `SupportsAcceleratorKeysFeatures` to check if this feature is supported. + +--- + +### IsPasswordAutoSaveEnabled + +Controls whether password information is automatically saved. + +**Type:** Boolean (Read/Write) + +**Default Value:** True + +**Example:** + +```vb +WebView21.IsPasswordAutoSaveEnabled = False +``` + +**Note:** Use `SupportsAutoFillFeatures` to check if this feature is supported. + +--- + +### IsGeneralAutoFillEnabled + +Controls whether general form information is saved and auto-filled. + +**Type:** Boolean (Read/Write) + +**Default Value:** True + +**Example:** + +```vb +WebView21.IsGeneralAutoFillEnabled = False +``` + +**Note:** Use `SupportsAutoFillFeatures` to check if this feature is supported. + +--- + +### IsPinchZoomEnabled + +Controls whether pinch gestures control zoom on touch devices. + +**Type:** Boolean (Read/Write) + +**Default Value:** True + +**Example:** + +```vb +WebView21.IsPinchZoomEnabled = False +``` + +**Note:** Use `SupportsPinchZoomFeatures` to check if this feature is supported. + +--- + +### IsSwipeNavigationEnabled + +Controls whether swipe gestures control page navigation on touch devices. + +**Type:** Boolean (Read/Write) + +**Default Value:** True + +**Example:** + +```vb +WebView21.IsSwipeNavigationEnabled = False +``` + +**Note:** Use `SupportsSwipeNavigationFeatures` to check if this feature is supported. + +--- + +### IsMuted + +Controls whether audio is muted from the webview. + +**Type:** Boolean (Read/Write) + +**Default Value:** False + +**Example:** + +```vb +WebView21.IsMuted = True +``` + +**Note:** Use `SupportsAudioFeatures` to check if this feature is supported. + +--- + +### IsDocumentPlayingAudio + +Indicates whether the WebView2 current document is playing audio. + +**Type:** Boolean (Read-only) + +**Example:** + +```vb +If WebView21.IsDocumentPlayingAudio Then + Debug.Print "Audio is playing" +End If +``` + +**Note:** Use `SupportsAudioFeatures` to check if this feature is supported. + +--- + +### IsSuspended + +Indicates whether WebView2 processing/rendering is suspended. + +**Type:** Boolean (Read-only) + +**Example:** + +```vb +If WebView21.IsSuspended Then + WebView21.Resume +End If +``` + +**Note:** Use `SupportsSuspendResumeFeatures` to check if this feature is supported. + +--- + +### IsDefaultDownloadDialogOpen + +Indicates whether the built-in download manager dialog is currently open. + +**Type:** Boolean (Read-only) + +**Example:** + +```vb +If WebView21.IsDefaultDownloadDialogOpen Then + WebView21.CloseDefaultDownloadDialog +End If +``` + +**Note:** Use `SupportsDownloadDialogFeatures` to check if this feature is supported. + +--- + +### EnvironmentOptions + +Environment options configuration object. + +**Type:** WebView2EnvironmentOptions (Read/Write) + +**Example:** + +```vb +WebView21.EnvironmentOptions.UserDataFolder = "C:\MyAppData" +``` + +See [WebView2EnvironmentOptions.md](WebView2EnvironmentOptions.md) for detailed documentation. + +--- + +### UseDeferredEvents + +Controls whether to use deferred event handling. + +**Type:** Boolean (Read/Write) + +**Default Value:** True + +**Example:** + +```vb +WebView21.UseDeferredEvents = False +``` + +--- + +### AdditionalAllowedFrameAncestors + +Sets additional allowed frame ancestors. + +**Type:** String (Read/Write) + +**Example:** + +```vb +WebView21.AdditionalAllowedFrameAncestors = "https://trusted-domain.com" +``` + +--- + +### BackColor + +The color applied when WebView2 loads. + +**Type:** OLE_COLOR (Read/Write) + +**Default Value:** &Ha0bd95 + +**Example:** + +```vb +WebView21.BackColor = vbWhite +``` + +--- + +### JsCallTimeOutSeconds + +Sets the JavaScript call timeout in seconds. + +**Type:** Double (Read/Write) + +**Example:** + +```vb +WebView21.JsCallTimeOutSeconds = 30 +``` + +--- + +## Feature Support Properties + +The following properties are used to check if specific features are supported: + +### SupportsNavigateCustomFeatures + +Indicates whether custom navigation features are supported. + +**Type:** Boolean (Read-only) + +**Return Condition:** CoreWebView2 is not Nothing + +--- + +### SupportsSuspendResumeFeatures + +Indicates whether suspend/resume features are supported. + +**Type:** Boolean (Read-only) + +**Return Condition:** CoreWebView3 is not Nothing + +--- + +### SupportsAudioFeatures + +Indicates whether audio features are supported. + +**Type:** Boolean (Read-only) + +**Return Condition:** CoreWebView8 is not Nothing + +--- + +### SupportsDownloadDialogFeatures + +Indicates whether download dialog features are supported. + +**Type:** Boolean (Read-only) + +**Return Condition:** CoreWebView9 is not Nothing + +--- + +### SupportsTaskManagerFeatures + +Indicates whether task manager features are supported. + +**Type:** Boolean (Read-only) + +**Return Condition:** CoreWebView7 is not Nothing + +--- + +### SupportsFolderMappingFeatures + +Indicates whether folder mapping features are supported. + +**Type:** Boolean (Read-only) + +**Return Condition:** CoreWebView5 is not Nothing + +--- + +### SupportsPdfFeatures + +Indicates whether PDF features are supported. + +**Type:** Boolean (Read-only) + +**Return Condition:** CoreWebView7 is not Nothing + +--- + +### SupportsUserAgentFeatures + +Indicates whether UserAgent features are supported. + +**Type:** Boolean (Read-only) + +**Return Condition:** Settings2 is not Nothing + +--- + +### SupportsAcceleratorKeysFeatures + +Indicates whether accelerator key features are supported. + +**Type:** Boolean (Read-only) + +**Return Condition:** Settings3 is not Nothing + +--- + +### SupportsAutoFillFeatures + +Indicates whether auto-fill features are supported. + +**Type:** Boolean (Read-only) + +**Return Condition:** Settings4 is not Nothing + +--- + +### SupportsPinchZoomFeatures + +Indicates whether pinch zoom features are supported. + +**Type:** Boolean (Read-only) + +**Return Condition:** Settings5 is not Nothing + +--- + +### SupportsSwipeNavigationFeatures + +Indicates whether swipe navigation features are supported. + +**Type:** Boolean (Read-only) + +**Return Condition:** Settings6 is not Nothing + +--- + +## Usage Examples + +### Check Feature Support + +```vb +If WebView21.SupportsPdfFeatures Then + WebView21.PrintToPdf "C:\output.pdf" +Else + MsgBox "PDF export not supported in this WebView2 version" +End If + +If WebView21.SupportsAudioFeatures Then + WebView21.IsMuted = True +End If +``` + +### Configure WebView2 + +```vb +With WebView21 + .IsScriptEnabled = True + .AreDefaultContextMenusEnabled = False + .AreDevToolsEnabled = False + .UserAgent = "MyApp/2.0" + .ZoomFactor = 1.0 +End With +``` + diff --git a/docs/PackageReference/Webview2/WebView2.md b/docs/PackageReference/Webview2/WebView2.md new file mode 100644 index 0000000..4923797 --- /dev/null +++ b/docs/PackageReference/Webview2/WebView2.md @@ -0,0 +1,325 @@ +--- +title: WebView2 Control +parent: WebView2 Package +nav_order: 4 +--- + +# WebView2 Control + +`WebView2` control is the core component of twinBASIC WebView2 package, providing complete functionality for embedding Microsoft Edge WebView2 controls in Windows applications. + +## Class Information + +| Property | Value | +| --------------- | -------------------------------------- | +| Class Name | `WebView2` | +| Base Class | `ControlAlt` | +| Interface | `IWindowsControl` | +| COM Creatable | Yes | +| Access Modifier | `Public` | +| Icon | `/miscellaneous/ICONS/WebView2_48.png` | + +## Overview + +WebView2 control is based on Microsoft Edge (Chromium) kernel, providing: + +- 🌐 Modern web content rendering +- 🔄 Bidirectional communication with JavaScript +- 📊 Complete encapsulation of WebView2 API +- 🎯 Simple and easy-to-use event-driven model +- 🚀 High-performance web application integration + +## Quick Start + +```vb +Private Sub Form_Load() + ' Note: All WebView21 member operations must be done after WebView21_Ready() + ' WebView21.DocumentURL = "https://www.twinbasic.com" +End Sub + +Private Sub WebView21_Ready() + ' Set initial URL + WebView21.DocumentURL = "https://www.twinbasic.com" + Debug.Print "WebView2 is ready!" +End Sub + +Private Sub WebView21_NavigationComplete(ByVal IsSuccess As Boolean, ByVal WebErrorStatus As Long) + If IsSuccess Then + Debug.Print "Navigation successful: " & WebView21.DocumentURL + Else + Debug.Print "Navigation failed: " & WebErrorStatus + End If +End Sub +``` + +## Properties Overview + +### Navigation Related + +| Property | Type | Description | +| --------------- | ------------------- | ---------------------- | +| `DocumentURL` | String (Read-only) | Current document URL | +| `DocumentTitle` | String (Read-only) | Current document title | +| `CanGoBack` | Boolean (Read-only) | Can go back | +| `CanGoForward` | Boolean (Read-only) | Can go forward | + +### Display Related + +| Property | Type | Description | +| ------------ | --------- | ----------------------------- | +| `ZoomFactor` | Double | Zoom factor (1.5 = 150%) | +| `IsMuted` | Boolean | Whether audio is muted | +| `BackColor` | OLE_COLOR | Background color when loading | + +### Configuration Related + +| Property | Type | Description | +| -------------------------------- | -------------------------- | ------------------------------------------ | +| `EnvironmentOptions` | WebView2EnvironmentOptions | Environment options configuration | +| `UseDeferredEvents` | Boolean | Whether to use deferred events | +| `IsScriptEnabled` | Boolean | Whether to enable JavaScript | +| `IsWebMessageEnabled` | Boolean | Whether to enable Web messages | +| `AreDefaultScriptDialogsEnabled` | Boolean | Whether to enable default script dialogs | +| `AreDevToolsEnabled` | Boolean | Whether to allow opening DevTools | +| `AreDefaultContextMenusEnabled` | Boolean | Whether to enable default right-click menu | +| `IsZoomControlEnabled` | Boolean | Whether to allow zooming | +| `UserAgent` | String | UserAgent string | + +### Feature Support Properties + +| Property | Description | +| -------------------------------- | -------------------------------------- | +| `SupportsNavigateCustomFeatures` | Whether custom navigation is supported | +| `SupportsSuspendResumeFeatures` | Whether suspend/resume is supported | +| `SupportsAudioFeatures` | Whether audio control is supported | +| `SupportsPdfFeatures` | Whether PDF export is supported | +| `SupportsTaskManagerFeatures` | Whether task manager is supported | + +> 💡 **Tip**: For detailed descriptions of all properties, please refer to [WebView2 Properties Complete Documentation](./WebView2-Properties.md). + +## Methods Overview + +### Navigation Methods + +| Method | Description | +| ------------------------------------------------ | ------------------------------ | +| `Navigate(uri)` | Navigate to specified URL | +| `NavigateCustom(uri, method, headers, postData)` | Custom HTTP request navigation | +| `NavigateToString(html)` | Load HTML string | +| `GoBack()` | Go back | +| `GoForward()` | Go forward | +| `Reload()` | Refresh | + +### JavaScript Interaction + +| Method | Description | +| -------------------------------- | ------------------------------- | +| `ExecuteScript(code)` | Execute JavaScript code | +| `JsRun(funcName, args())` | Synchronously call JS function | +| `JsRunAsync(funcName, args())` | Asynchronously call JS function | +| `JsProp(propName)` | Get JS property value | +| `PostWebMessage(message)` | Send message to JavaScript | +| `AddObject(name, obj, deferred)` | Expose COM object to JavaScript | +| `RemoveObject(name)` | Remove exposed object | + +### Resource Management + +| Method | Description | +| --------------------------------------- | --------------------------- | +| `AddWebResourceRequestedFilter()` | Add resource request filter | +| `RemoveWebResourceRequestedFilter()` | Remove filter | +| `AddScriptToExecuteOnDocumentCreated()` | Add page load script | + +### Advanced Features + +| Method | Description | +| ------------------------------------- | ----------------------------- | +| `OpenDevToolsWindow()` | Open developer tools | +| `CallDevToolsProtocolMethod()` | Call DevTools protocol method | +| `Suspend()` | Suspend WebView2 | +| `Resume()` | Resume WebView2 | +| `PrintToPdf()` | Export to PDF | +| `SetVirtualHostNameToFolderMapping()` | Set virtual host mapping | + +> 💡 **Tip**: For detailed descriptions and examples of all methods, please refer to [WebView2 Methods Complete Documentation](./WebView2-Methods.md). + +## Events + +### Lifecycle Events + +| Event | Description | +| ---------- | ------------------------------------------------------------------------------ | +| `Create()` | Fired before WebView2 control is created, used to configure EnvironmentOptions | +| `Ready()` | Fired after WebView2 control creation completes and is ready | +| `Error()` | Fired when an error occurs during initialization | + +### Navigation Events + +| Event | Description | +| ------------------------ | ----------------------------------------------------- | +| `NavigationStarting()` | Fired before navigation starts, can cancel navigation | +| `NavigationComplete()` | Fired after navigation completes | +| `SourceChanged()` | Fired when DocumentURL property is updated | +| `DocumentTitleChanged()` | Fired when document title is updated | +| `DOMContentLoaded()` | Fired after DOM document is fully loaded | + +### User Interaction Events + +| Event | Description | +| ------------------------- | ------------------------------------------------------------------------------- | +| `PermissionRequested()` | Fired when web page requests permissions | +| `AcceleratorKeyPressed()` | Fired when shortcut key is pressed | +| `UserContextMenu()` | Fired when user right-clicks (requires `AreDefaultContextMenusEnabled = False`) | + +### Script and Message Events + +| Event | Description | +| ----------------------- | ---------------------------------------------------------------------------------- | +| `ScriptDialogOpening()` | Fired when script dialog opens (requires `AreDefaultScriptDialogsEnabled = False`) | +| `JsAsyncResult()` | Asynchronous JavaScript call returns result | +| `JsMessage()` | Fired when JavaScript sends message (via `window.chrome.webview.postMessage`) | + +### Resource and Download Events + +| Event | Description | +| ------------------------ | ----------------------------------------------------- | +| `WebResourceRequested()` | Fired when matching Web resource request occurs | +| `DownloadStarting()` | Fired when download starts, can modify path or cancel | + +### System Events + +| Event | Description | +| ---------------------------- | ---------------------------------- | +| `ProcessFailed()` | Fired when external process fails | +| `NewWindowRequested()` | Fired when new window is requested | +| `SuspendCompleted()` | Suspend successful completion | +| `SuspendFailed()` | Suspend failed | +| `PrintToPdfCompleted()` | PDF print successful | +| `PrintToPdfFailed()` | PDF print failed | +| `DevToolsProtocolResponse()` | DevTools protocol response | + +> 💡 **Tip**: For detailed parameter and usage descriptions of each event, please refer to [WebView2 Events Complete Documentation](./WebView2-Events.md). + +## Usage Examples + +### Basic Usage + +```vb +Private Sub Form_Load() + ' Note: All WebView21 member operations must be done after WebView21_Ready() +End Sub + +Private Sub WebView21_Ready() + ' Set initial URL + WebView21.DocumentURL = "https://www.twinbasic.com" + Debug.Print "WebView2 is ready!" +End Sub + +Private Sub WebView21_NavigationComplete(ByVal IsSuccess As Boolean, ByVal WebErrorStatus As Long) + If IsSuccess Then + Debug.Print "Navigation successful: " & WebView21.DocumentURL + Else + Debug.Print "Navigation failed: " & WebErrorStatus + End If +End Sub +``` + +### JavaScript Interaction + +```vb +' Execute JavaScript code +WebView21.ExecuteScript "alert('Hello from VB6!')" + +' Synchronously call JavaScript function +Dim title As String +title = WebView21.JsProp("document.title") +Me.Caption = title + +' Asynchronously call JavaScript function +Dim token As LongLong +token = WebView21.JsRunAsync("fetchData", "api/data") + +Private Sub WebView21_JsAsyncResult(ByVal Result As Variant, Token As LongLong, ErrString As String) + If Token = token Then + Debug.Print "Async return result: " & Result + End If +End Sub +``` + +### Receive JavaScript Messages + +```vb +Private Sub WebView21_JsMessage(ByVal Message As Variant) + If VarType(Message) = vbObject Then + Dim msg As Object + Set msg = Message + If msg.Exists("type") And msg("type") = "alert" Then + MsgBox msg("message") + End If + End If +End Sub +``` + +JavaScript side: + +```javascript +window.chrome.webview.postMessage({ + type: "alert", + message: "Hello from JavaScript!", +}); +``` + +### Intercept Web Requests + +```vb +Private Sub WebView21_Ready() + ' Add resource filter + WebView21.AddWebResourceRequestedFilter "*.js", wv2WebResourceContext.wv2All +End Sub + +Private Sub WebView21_WebResourceRequested(ByVal Request As WebView2Request, _ + ByVal Response As WebView2Response) + ' Block specific script + If InStr(Request.Uri, "analytics.js") > 0 Then + Response.StatusCode = 404 + Response.ReasonPhrase = "Not Found" + End If +End Sub +``` + +### PDF Export + +```vb +Private Sub cmdExportPDF_Click() + If WebView21.SupportsPdfFeatures Then + WebView21.PrintToPdf "C:\Documents\export.pdf", _ + wv2PrintOrientation.wv2PrintPortrait, _ + , , , , , , , True + Else + MsgBox "PDF export not supported" + End If +End Sub + +Private Sub WebView21_PrintToPdfCompleted() + MsgBox "PDF export successful!" +End Sub +``` + +## Notes + +1. **Runtime Requirement**: System needs to have WebView2 Runtime (Evergreen) installed +2. **Ready Event**: Can only call most methods after `Ready` event is triggered +3. **Thread Safety**: Use `UseDeferredEvents` to avoid re-entrancy problems +4. **Memory Management**: Release COM objects in time to avoid memory leaks +5. **Error Handling**: Properly handle initialization failures in `Error` event + +## Related Documents + +- [WebView2 Events Detailed Documentation](./WebView2-Events.md) +- [WebView2 Properties Detailed Documentation](./WebView2-Properties.md) +- [WebView2 Methods Detailed Documentation](./WebView2-Methods.md) +- [WebView2 Environment Options](./WebView2EnvironmentOptions.md) +- [Enumeration Types](./Enumerations.md) +- [Deferred Callback Mechanism](./DeferredCallback.md) +- [Quick Start Guide](./Getting-started.md) + diff --git a/docs/PackageReference/Webview2/WebView2EnvironmentOptions.md b/docs/PackageReference/Webview2/WebView2EnvironmentOptions.md new file mode 100644 index 0000000..ce4740d --- /dev/null +++ b/docs/PackageReference/Webview2/WebView2EnvironmentOptions.md @@ -0,0 +1,295 @@ +--- +title: EnvironmentOptions +parent: WebView2 Package +nav_order: 9 +--- + +# WebView2EnvironmentOptions Class + +`WebView2EnvironmentOptions` class is used to configure WebView2 environment options. These options must be set before or during WebView2 creation to take effect. + +## Class Information + +| Property | Value | +| -------------- | ----------------------------------------------------- | +| Class Name | `WebView2EnvironmentOptions` | +| ClassId | `185E63C0-E641-47ED-B6A9-8565168A7FCF` | +| InterfaceId | `E610040A-F023-4DC4-A766-2C2B75BDCC11` | +| COM Creatable | No | +| Access Modifier| `Private` (accessed via WebView2.EnvironmentOptions) | + +## Properties + +### BrowserExecutableFolder + +```vb +Public BrowserExecutableFolder As String +``` + +Specifies the folder path for WebView2 runtime browser executable. + +- If left empty, system default WebView2 runtime will be used +- Can be used to specify a fixed version of WebView2 runtime + +**Note:** Must be set before or during the `Create` event. + +**Example:** + +```vb +Private Sub WebView21_Create() + WebView21.EnvironmentOptions.BrowserExecutableFolder = _ + "C:\\WebView2Runtime\\106.0.1370.47" +End Sub +``` + +--- + +### UserDataFolder + +```vb +Public UserDataFolder As String +``` + +Specifies the path for the user data folder, used to store browser data (cookies, cache, local storage, etc.). + +- If left empty, default location will be used +- Each WebView2 instance needs an independent user data folder or subfolder +- Folder path cannot be too long, otherwise creation may fail + +**Note:** Must be set before or during the `Create` event. + +**Example:** + +```vb +Private Sub WebView21_Create() + WebView21.EnvironmentOptions.UserDataFolder = _ + Environ("APPDATA") & "\\MyApp\\WebView2Data" +End Sub +``` + +**Best Practices:** + +- Place user data folder in application data directory +- Use independent subfolder for each instance to avoid locking issues +- Refer to [Customize the UserDataFolder](./Customize-the-UserDataFolder.md) for more information + +--- + +### AdditionalBrowserArguments + +```vb +Public AdditionalBrowserArguments As String +``` + +Specifies additional arguments to pass to the browser core. + +**Note:** Must be set before or during the `Create` event. + +**Common Arguments:** + +| Argument | Description | +| -------------------------------------------- | ---------------------------------- | +| `--disable-extensions` | Disable extensions | +| `--disable-web-security` | Disable web security (dev only) | +| `--allow-file-access-from-files` | Allow local file access | +| `--autoplay-policy=no-user-gesture-required` | Autoplay media without user gesture | + +**Example:** + +```vb +Private Sub WebView21_Create() + WebView21.EnvironmentOptions.AdditionalBrowserArguments = _ + "--disable-extensions --autoplay-policy=no-user-gesture-required" +End Sub +``` + +--- + +### Language + +```vb +Public Language As String +``` + +Specifies the language used by the browser, affects `Accept-Language` HTTP header. + +- Use RFC 4646 language tag format, such as `"en-US"`, `"zh-CN"` +- Multiple languages separated by commas + +**Note:** Must be set before or during the `Create` event. + +**Example:** + +```vb +Private Sub WebView21_Create() + WebView21.EnvironmentOptions.Language = "en-US,en;q=0.9,zh;q=0.8" +End Sub +``` + +--- + +### TargetCompatibleBrowserVersion + +```vb +Public TargetCompatibleBrowserVersion As String = "86.0.616.0" +``` + +Specifies the minimum required WebView2 runtime version. + +- Default: `"86.0.616.0"` +- If system WebView2 version is lower than this value, creation will fail + +**Note:** Must be set before or during the `Create` event. + +**Example:** + +```vb +Private Sub WebView21_Create() + ' Require WebView2 Runtime 100.0 or higher + WebView21.EnvironmentOptions.TargetCompatibleBrowserVersion = "100.0.1185.36" +End Sub +``` + +--- + +### AllowSingleSignOnUsingOSPrimaryAccount + +```vb +Public AllowSingleSignOnUsingOSPrimaryAccount As Boolean +``` + +Whether to allow using OS primary account for single sign-on (SSO). + +- Default: `False` +- When enabled, WebView2 can use credentials of the currently logged-in Windows user for authentication + +**Note:** Must be set before or during the `Create` event. + +**Example:** + +```vb +Private Sub WebView21_Create() + WebView21.EnvironmentOptions.AllowSingleSignOnUsingOSPrimaryAccount = True +End Sub +``` + +--- + +### ExclusiveUserDataFolderAccess + +```vb +Public ExclusiveUserDataFolderAccess As Boolean +``` + +Whether to require exclusive access to the user data folder. + +- Default: `False` +- When enabled, if user data folder is already in use by another WebView2 instance, creation will fail + +**Note:** Must be set before or during the `Create` event. + +**Example:** + +```vb +Private Sub WebView21_Create() + WebView21.EnvironmentOptions.ExclusiveUserDataFolderAccess = True +End Sub +``` + +--- + +### EnableTrackingPrevention + +```vb +Public EnableTrackingPrevention As Boolean = True +``` + +Whether to enable tracking prevention feature. + +- Default: `True` +- When enabled, WebView2 will block known trackers + +**Note:** Must be set before or during the `Create` event. + +**Example:** + +```vb +Private Sub WebView21_Create() + ' Disable tracking prevention + WebView21.EnvironmentOptions.EnableTrackingPrevention = False +End Sub +``` + +## Usage Examples + +### Complete Configuration Example + +```vb +Private Sub WebView21_Create() + With WebView21.EnvironmentOptions + ' Specify user data folder + .UserDataFolder = Environ("LOCALAPPDATA") & "\\MyApp\\WebView2" + + ' Set language + .Language = "en-US" + + ' Enable single sign-on + .AllowSingleSignOnUsingOSPrimaryAccount = True + + ' Enable tracking prevention + .EnableTrackingPrevention = True + + ' Additional browser arguments + .AdditionalBrowserArguments = "--autoplay-policy=no-user-gesture-required" + + ' Set minimum version requirement + .TargetCompatibleBrowserVersion = "100.0.0.0" + End With +End Sub +``` + +### Multi-Instance Configuration + +When multiple WebView2 instances are needed, each instance should use an independent user data subfolder: + +```vb +Private InstanceCount As Long = 0 + +Private Sub CreateWebViewWithUniqueFolder() + Dim wv As New WebView2 + InstanceCount = InstanceCount + 1 + + ' Use Create event handler to dynamically set + AddHandler wv.Create, AddressOf WebView_Create + + Controls.Add wv +End Sub + +Private Sub WebView_Create(Sender As Object) + Dim wv As WebView2 = CType(Sender, WebView2) + wv.EnvironmentOptions.UserDataFolder = _ + Environ("LOCALAPPDATA") & "\\MyApp\\WebView2_" & InstanceCount +End Sub +``` + +**Note:** The WebView2 class has implemented an automatic retry mechanism internally. When the user data folder is locked, it will automatically try to create a subfolder. + +## Property Setting Timing + +| Property | Setting Timing | +| -------------------------------------------- | ----------------------- | +| `BrowserExecutableFolder` | Before/during Create event | +| `UserDataFolder` | Before/during Create event | +| `AdditionalBrowserArguments` | Before/during Create event | +| `Language` | Before/during Create event | +| `TargetCompatibleBrowserVersion` | Before/during Create event | +| `AllowSingleSignOnUsingOSPrimaryAccount` | Before/during Create event | +| `ExclusiveUserDataFolderAccess` | Before/during Create event | +| `EnableTrackingPrevention` | Before/during Create event | + +## Notes + +1. **Setting Timing**: All properties must be set before or during the `Create` event, setting afterwards has no effect +2. **User Data Folder**: Ensure the application has read/write permissions for the specified user data folder +3. **Version Compatibility**: `TargetCompatibleBrowserVersion` should not be set too high, otherwise may not run on older systems +4. **Argument Security**: Arguments in `AdditionalBrowserArguments` may affect security, use cautiously in production environment diff --git a/docs/PackageReference/Webview2/WebView2Header.md b/docs/PackageReference/Webview2/WebView2Header.md new file mode 100644 index 0000000..4066943 --- /dev/null +++ b/docs/PackageReference/Webview2/WebView2Header.md @@ -0,0 +1,336 @@ +--- +title: Header +parent: WebView2 Package +nav_order: 15 +--- + +# WebView2Header Class + +The `WebView2Header` class represents a single HTTP header information, containing header name and header value. + +## Class Information + +| Property | Value | +| --------- | -------------------- | +| Class Name | `WebView2Header` | +| COM Creatable | No | + +## Properties + +### Name + +```vb +Public Name As String +``` + +The name of the HTTP header. + +**Type:** `String` + +**Example:** + +```vb +Dim header As WebView2Header +header.Name = "Content-Type" +``` + +### Value + +```vb +Public Value As String +``` + +The value of the HTTP header. + +**Type:** `String` + +**Example:** + +```vb +Dim header As WebView2Header +header.Value = "application/json" +``` + +## Constructor + +```vb +Public Sub New(ByVal Name As String, ByVal Value As String) +``` + +Creates a new `WebView2Header` object. + +**Parameters:** + +- `Name` - Header name +- `Value` - Header value + +**Example:** + +```vb +Dim header As New WebView2Header("Content-Type", "text/html") +Debug.Print header.Name & ": " & header.Value +' Output: Content-Type: text/html +``` + +## Usage Scenarios + +### 1. Create Custom Header Object + +```vb +' Create single header object +Dim authHeader As New WebView2Header("Authorization", "Bearer token123") +Debug.Print authHeader.Name & ": " & authHeader.Value + +' Create multiple headers +Dim headers() As WebView2Header +ReDim headers(2) +Set headers(0) = New WebView2Header("Content-Type", "application/json") +Set headers(1) = New WebView2Header("Accept", "application/json") +Set headers(2) = New WebView2Header("User-Agent", "MyApp/1.0") + +Dim i As Long +For i = LBound(headers) To UBound(headers) + Debug.Print headers(i).Name & ": " & headers(i).Value +Next +``` + +### 2. Access in Enumeration + +```vb +Private Sub WebView21_NavigationStarting(ByVal Uri As String, _ + ByVal IsUserInitiated As Boolean, ByVal IsRedirected As Boolean, _ + ByVal RequestHeaders As WebView2RequestHeaders, ByRef Cancel As Boolean) + + Dim header As WebView2Header + For Each header In RequestHeaders + Debug.Print "Name: " & header.Name + Debug.Print "Value: " & header.Value + Debug.Print "---" + Next +End Sub +``` + +### 3. Header Validation + +```vb +Private Function ValidateHeader(ByVal header As WebView2Header) As Boolean + ' Check if header name is valid + If Len(header.Name) = 0 Then + Debug.Print "Error: Header name is empty" + ValidateHeader = False + Exit Function + End If + + ' Check if header name contains illegal characters + Dim invalidChars As String + invalidChars = "()<>@,;:\""/[]?={} \t" + + Dim i As Long + For i = 1 To Len(invalidChars) + If InStr(header.Name, Mid(invalidChars, i, 1)) > 0 Then + Debug.Print "Error: Header name contains illegal characters" + ValidateHeader = False + Exit Function + End If + Next + + ValidateHeader = True +End Function + +' Usage example +Dim testHeader As New WebView2Header("Invalid-Name()", "value") +If Not ValidateHeader(testHeader) Then + Debug.Print "Header validation failed" +End If +``` + +### 4. Header Conversion + +```vb +' Convert header object to string +Function HeaderToString(ByVal header As WebView2Header) As String + HeaderToString = header.Name & ": " & header.Value +End Function + +' Usage example +Dim header As New WebView2Header("Content-Type", "application/json") +Debug.Print HeaderToString(header) +' Output: Content-Type: application/json + +' Convert header object array to string +Function HeadersToString(headers() As WebView2Header) As String + Dim result As String + Dim i As Long + + For i = LBound(headers) To UBound(headers) + result = result & headers(i).Name & ": " & headers(i).Value & vbCrLf + Next + + HeadersToString = result +End Function +``` + +### 5. Header Filtering + +```vb +' Filter specific headers +Private Sub FilterHeaders(ByVal RequestHeaders As WebView2RequestHeaders) + Dim header As WebView2Header + + For Each header In RequestHeaders + Select Case LCase(header.Name) + Case "authorization" + Debug.Print "Found authorization header: " & Left(header.Value, 10) & "..." + Case "cookie" + Debug.Print "Found Cookie header" + Case "user-agent" + Debug.Print "User Agent: " & header.Value + End Select + Next +End Sub +``` + +### 6. Header Cloning + +```vb +' Clone header object +Function CloneHeader(ByVal header As WebView2Header) As WebView2Header + Set CloneHeader = New WebView2Header(header.Name, header.Value) +End Function + +' Clone header object array +Function CloneHeaders(headers() As WebView2Header) As WebView2Header() + Dim result() As WebView2Header + ReDim result(UBound(headers)) + + Dim i As Long + For i = LBound(headers) To UBound(headers) + Set result(i) = CloneHeader(headers(i)) + Next + + CloneHeaders = result +End Function + +' Usage example +Dim originalHeader As New WebView2Header("X-Custom", "value1") +Dim clonedHeader As WebView2Header +Set clonedHeader = CloneHeader(originalHeader) + +' Modifying clone doesn't affect original object +clonedHeader.Value = "value2" +Debug.Print originalHeader.Value ' Output: value1 +Debug.Print clonedHeader.Value ' Output: value2 +``` + +### 7. Header Comparison + +```vb +' Compare two header objects +Function HeadersEqual(ByVal header1 As WebView2Header, _ + ByVal header2 As WebView2Header) As Boolean + HeadersEqual = (LCase(header1.Name) = LCase(header2.Name) And _ + header1.Value = header2.Value) +End Function + +' Usage example +Dim header1 As New WebView2Header("Content-Type", "application/json") +Dim header2 As New WebView2Header("Content-Type", "application/json") +Dim header3 As New WebView2Header("content-type", "application/json") ' Different case + +Debug.Print HeadersEqual(header1, header2) ' Output: True +Debug.Print HeadersEqual(header1, header3) ' Output: True (case-insensitive name) +``` + +### 8. Header Collection Operations + +```vb +' Find header +Function FindHeader(headers() As WebView2Header, ByVal name As String) As WebView2Header + Dim i As Long + For i = LBound(headers) To UBound(headers) + If LCase(headers(i).Name) = LCase(name) Then + Set FindHeader = headers(i) + Exit Function + End If + Next + Set FindHeader = Nothing +End Function + +' Add header (if doesn't exist) +Sub AddHeaderIfNotExists(headers() As WebView2Header, _ + ByVal name As String, ByVal value As String) + If FindHeader(headers, name) Is Nothing Then + Dim newSize As Long + newSize = UBound(headers) + 1 + ReDim Preserve headers(newSize) + Set headers(newSize) = New WebView2Header(name, value) + End If +End Sub + +' Usage example +Dim headers() As WebView2Header +ReDim headers(0) +Set headers(0) = New WebView2Header("Content-Type", "text/html") + +AddHeaderIfNotExists headers, "Content-Type", "application/json" +AddHeaderIfNotExists headers, "Authorization", "Bearer token" + +Debug.Print "Header count: " & UBound(headers) + 1 ' Output: 2 +``` + +## Common HTTP Header Types + +### Request Headers + +```vb +Dim userAgent As New WebView2Header("User-Agent", "MyApp/1.0") +Dim accept As New WebView2Header("Accept", "application/json") +Dim contentType As New WebView2Header("Content-Type", "application/json") +Dim authorization As New WebView2Header("Authorization", "Bearer token123") +Dim cookie As New WebView2Header("Cookie", "session_id=abc123") +``` + +### Response Headers + +```vb +Dim contentType As New WebView2Header("Content-Type", "text/html; charset=utf-8") +Dim contentLength As New WebView2Header("Content-Length", "1024") +Dim cacheControl As New WebView2Header("Cache-Control", "no-cache") +Dim setCookie As New WebView2Header("Set-Cookie", "session_id=xyz789; Path=/; HttpOnly") +Dim server As New WebView2Header("Server", "MyServer/1.0") +``` + +### Security Headers + +```vb +Dim xContentTypeOptions As New WebView2Header("X-Content-Type-Options", "nosniff") +Dim xFrameOptions As New WebView2Header("X-Frame-Options", "DENY") +Dim xXssProtection As New WebView2Header("X-XSS-Protection", "1; mode=block") +Dim strictTransportSecurity As New WebView2Header("Strict-Transport-Security", "max-age=31536000") +``` + +### CORS Headers + +```vb +Dim accessControlAllowOrigin As New WebView2Header("Access-Control-Allow-Origin", "*") +Dim accessControlAllowMethods As New WebView2Header("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE") +Dim accessControlAllowHeaders As New WebView2Header("Access-Control-Allow-Headers", "Content-Type, Authorization") +``` + +## Notes + +1. **Case Sensitivity:** HTTP header names are case-insensitive, use `LCase` or `UCase` functions when comparing. + +2. **Space Handling:** Spaces in header names and values are significant, don't trim them arbitrarily. + +3. **Multi-value Headers:** Some headers may have multiple values (such as `Set-Cookie`), `WebView2Header` only stores a single value, multiple values need multiple `WebView2Header` objects. + +4. **Special Characters:** Header names should avoid containing special characters, some characters are illegal. + +5. **Length Limits:** HTTP headers have length limits (usually 8KB or more), overly long headers may cause issues. + +6. **Encoding Issues:** Header values are typically ASCII characters, non-ASCII characters may need encoding. + +7. **Read-only Properties:** `WebView2Header` objects obtained in `WebResourceRequested` event are read-only, modifications won't affect the actual request. To modify headers, use `RequestHeaders` or `ResponseHeaders` object methods. + +8. **Object Lifecycle:** `WebView2Header` objects are typically created and managed by `WebView2HeadersCollection`, no need for manual creation and destruction. diff --git a/docs/PackageReference/Webview2/WebView2HeadersCollection.md b/docs/PackageReference/Webview2/WebView2HeadersCollection.md new file mode 100644 index 0000000..dcfc0e8 --- /dev/null +++ b/docs/PackageReference/Webview2/WebView2HeadersCollection.md @@ -0,0 +1,233 @@ +--- +title: HeadersCollection +parent: WebView2 Package +nav_order: 14 +--- + +# WebView2HeadersCollection Class + +The `WebView2HeadersCollection` class is used to enumerate and manage HTTP header collections. This class implements the `IEnumVARIANT` interface and supports `For Each` enumeration. + +## Class Information + +| Property | Value | +| --------- | ------------------------------ | +| Class Name | `WebView2HeadersCollection` | +| COM Creatable | No | +| Implemented Interface | `IEnumVARIANT` | + +## Interface Implementation + +### IEnumVARIANT Interface Methods + +This class implements the standard COM enumeration interface, primarily used via `For Each` syntax. + +```vb +For Each header In HeadersCollection + ' Process each header +Next +``` + +## Usage Scenarios + +### 1. Enumerate All Request Headers + +```vb +Private Sub WebView21_NavigationStarting(ByVal Uri As String, _ + ByVal IsUserInitiated As Boolean, ByVal IsRedirected As Boolean, _ + ByVal RequestHeaders As WebView2RequestHeaders, ByRef Cancel As Boolean) + + Debug.Print "=== Request Header List ===" + + Dim header As WebView2Header + For Each header In RequestHeaders + Debug.Print header.Name & ": " & header.Value + Next +End Sub +``` + +**Sample Output:** + +``` +=== Request Header List === +Host: www.example.com +User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) ... +Accept: text/html,application/xhtml+xml,application/xml;q=0.9 +Accept-Language: en-US,en;q=0.9 +Connection: keep-alive +``` + +### 2. Enumerate All Headers with a Specific Name + +```vb +Private Sub WebView21_NavigationStarting(ByVal Uri As String, _ + ByVal IsUserInitiated As Boolean, ByVal IsRedirected As Boolean, _ + ByVal RequestHeaders As WebView2RequestHeaders, ByRef Cancel As Boolean) + + ' Get all Set-Cookie headers (if there are multiple) + Dim cookieHeaders As WebView2HeadersCollection + Set cookieHeaders = RequestHeaders.GetHeaders("Set-Cookie") + + If Not cookieHeaders Is Nothing Then + Dim header As WebView2Header + For Each header In cookieHeaders + Debug.Print "Cookie: " & header.Value + Next + End If +End Sub +``` + +### 3. Enumerate Response Headers + +```vb +Private Sub WebView21_WebResourceRequested(ByVal Request As WebView2Request, _ + ByVal Response As WebView2Response) + + ' Set custom response + Response.StatusCode = 200 + Response.ReasonPhrase = "OK" + Response.ContentUTF8 = "Test" + + ' Add multiple response headers + Response.Headers.AppendHeader "Content-Type", "text/html" + Response.Headers.AppendHeader "Cache-Control", "no-cache" + Response.Headers.AppendHeader "X-Custom-Header", "CustomValue" + + ' Enumerate all response headers (for debugging) + Debug.Print "=== Response Header List ===" + Dim header As WebView2Header + For Each header In Response.Headers + Debug.Print header.Name & ": " & header.Value + Next +End Sub +``` + +### 4. Filter Specific Type of Headers + +```vb +Private Sub WebView21_NavigationStarting(ByVal Uri As String, _ + ByVal IsUserInitiated As Boolean, ByVal IsRedirected As Boolean, _ + ByVal RequestHeaders As WebView2RequestHeaders, ByRef Cancel As Boolean) + + ' Only show security-related headers + Debug.Print "=== Security-Related Headers ===" + + Dim header As WebView2Header + For Each header In RequestHeaders + If LCase(header.Name) = "authorization" Or _ + LCase(header.Name) = "cookie" Or _ + LCase(header.Name) = "x-api-key" Then + Debug.Print header.Name & ": " & header.Value + End If + Next +End Sub +``` + +### 5. Header Statistics + +```vb +Private Sub WebView21_NavigationStarting(ByVal Uri As String, _ + ByVal IsUserInitiated As Boolean, ByVal IsRedirected As Boolean, _ + ByVal RequestHeaders As WebView2RequestHeaders, ByRef Cancel As Boolean) + + Dim count As Long + Dim totalLength As Long + + Dim header As WebView2Header + For Each header In RequestHeaders + count = count + 1 + totalLength = totalLength + Len(header.Name) + Len(header.Value) + Next + + Debug.Print "Header count: " & count + Debug.Print "Total length: " & totalLength & " bytes" +End Sub +``` + +### 6. Header Copying + +```vb +Private Sub WebView21_WebResourceRequested(ByVal Request As WebView2Request, _ + ByVal Response As WebView2Response) + + ' Copy request headers to response (example scenario: proxy server) + Dim header As WebView2Header + For Each header In Request.Headers + ' Only copy specific headers + If LCase(header.Name) <> "host" And LCase(header.Name) <> "connection" Then + Response.Headers.AppendHeader header.Name, header.Value + End If + Next + + ' Add proxy identification + Response.Headers.AppendHeader "X-Forwarded-For", "192.168.1.1" + Response.Headers.AppendHeader "Via", "1.1 proxy-server" +End Sub +``` + +### 7. Header Validation + +```vb +Private Function ValidateHeaders(ByVal RequestHeaders As WebView2RequestHeaders) As Boolean + ' Check if required headers exist + Dim requiredHeaders As Variant + requiredHeaders = Array("Host", "User-Agent") + + Dim i As Long + Dim header As WebView2Header + Dim found As Boolean + + For i = LBound(requiredHeaders) To UBound(requiredHeaders) + found = False + For Each header In RequestHeaders + If LCase(header.Name) = LCase(requiredHeaders(i)) Then + found = True + Exit For + End If + Next + If Not found Then + Debug.Print "Missing required header: " & requiredHeaders(i) + ValidateHeaders = False + Exit Function + End If + Next + + ValidateHeaders = True +End Function +``` + +## WebView2Header Object + +The `WebView2Header` object represents a single HTTP header, containing the following properties: + +| Property | Type | Description | +| -------- | ------- | ------------- | +| `Name` | `String` | Header name | +| `Value` | `String` | Header value | + +**Example:** + +```vb +Dim header As WebView2Header +For Each header In RequestHeaders + Debug.Print "Name: " & header.Name + Debug.Print "Value: " & header.Value + Debug.Print "Length: " & Len(header.Name) & " + " & Len(header.Value) +Next +``` + +## Notes + +1. **Enumeration Order:** The order of header enumeration may not exactly match the insertion order. + +2. **Case Insensitivity:** HTTP header names are case-insensitive, but enumeration returns the original case. + +3. **Read-only Enumeration:** `WebView2HeadersCollection` is primarily used for enumeration, headers cannot be modified through enumeration. To modify headers, use `RequestHeaders` or `ResponseHeaders` object methods. + +4. **Empty Collections:** If there are no header information, enumeration will not throw exceptions, the `For Each` loop will not execute any iterations. + +5. **Performance Considerations:** Enumeration of requests with many headers may take some time. If you only need to get specific headers, prioritize using `GetHeader` or `Contains` methods. + +6. **Thread Safety:** Enumeration operations should be performed in the main thread or event handling context, avoid using in multi-threaded environments. + +7. **Implementation Limitations:** The `Skip`, `Reset`, `Clone` methods are currently unimplemented (return `E_NOTIMPL`), only `For Each` syntax can be used for enumeration. diff --git a/docs/PackageReference/Webview2/WebView2Request.md b/docs/PackageReference/Webview2/WebView2Request.md new file mode 100644 index 0000000..cc101aa --- /dev/null +++ b/docs/PackageReference/Webview2/WebView2Request.md @@ -0,0 +1,259 @@ +--- +title: Request +parent: WebView2 Package +nav_order: 10 +--- + +# WebView2Request Class + +The `WebView2Request` class encapsulates web resource request information, used in `WebResourceRequested` event and `NavigationStarting` event to access request details. + +## Class Information + +| Property | Value | +| --------- | --------------------- | +| Class Name | `WebView2Request` | +| COM Creatable | No (internal use) | +| Access Modifier | `Public` | + +## Properties + +### Method + +```vb +Public Property Get Method() As String +``` + +Gets the HTTP request method. + +**Return Values:** + +- `"GET"` - Get resource +- `"POST"` - Submit data +- `"PUT"` - Update resource +- `"DELETE"` - Delete resource +- `"HEAD"`, `"OPTIONS"`, `"PATCH"`, etc. + +**Example:** + +```vb +Private Sub WebView21_WebResourceRequested(ByVal Request As WebView2Request, _ + ByVal Response As WebView2Response) + + If Request.Method = "POST" Then + Debug.Print "POST request to: " & Request.Uri + End If +End Sub +``` + +--- + +### Uri + +```vb +Public Property Get Uri() As String +``` + +Gets the complete URI of the request. + +**Example:** + +```vb +Private Sub WebView21_WebResourceRequested(ByVal Request As WebView2Request, _ + ByVal Response As WebView2Response) + + Debug.Print "Request URI: " & Request.Uri + ' Output: https://api.example.com/data?id=123 +End Sub +``` + +--- + +### Headers + +```vb +Public Property Get Headers() As WebView2RequestHeaders +``` + +Gets the HTTP headers collection of the request. + +Returns [WebView2RequestHeaders](./WebView2RequestHeaders.md) object, used to access and modify request headers. + +**Example:** + +```vb +Private Sub WebView21_WebResourceRequested(ByVal Request As WebView2Request, _ + ByVal Response As WebView2Response) + + ' Get User-Agent + Dim userAgent As String + userAgent = Request.Headers.GetHeader("User-Agent") + Debug.Print "User-Agent: " & userAgent + + ' Check if Authorization header exists + If Request.Headers.Contains("Authorization") Then + Debug.Print "Request has authorization" + End If +End Sub +``` + +--- + +### ContentBytes + +```vb +Public Property Get ContentBytes() As Variant +Public Property Let ContentBytes(Value As Variant) +``` + +Gets or sets the request content (byte array). + +**Description:** + +- Return type is `Byte()` array or `Empty` (no content) +- Typically used for request body of POST/PUT requests + +**Example:** + +```vb +Private Sub WebView21_WebResourceRequested(ByVal Request As WebView2Request, _ + ByVal Response As WebView2Response) + + Dim content As Variant + content = Request.ContentBytes + + If Not IsEmpty(content) Then + ' Convert to string for display + Dim contentStr As String + contentStr = StrConv(content, vbUnicode) + Debug.Print "Request body: " & contentStr + End If +End Sub +``` + +--- + +### ContentUTF8 + +```vb +Public Property Get ContentUTF8() As String +Public Property Let ContentUTF8(ByVal Value As String) +``` + +Gets or sets the request content (UTF-8 encoded string). + +**Description:** + +- Automatically handles UTF-8 encoding and decoding +- Suitable for text-type request bodies (JSON, form data, etc.) + +**Example:** + +```vb +Private Sub WebView21_WebResourceRequested(ByVal Request As WebView2Request, _ + ByVal Response As WebView2Response) + + Dim jsonContent As String + jsonContent = Request.ContentUTF8 + + ' Parse JSON content + If InStr(jsonContent, "username") > 0 Then + Debug.Print "Contains username field" + End If +End Sub +``` + +## Usage Scenarios + +### 1. Intercept and Modify Requests + +```vb +Private Sub WebView21_WebResourceRequested(ByVal Request As WebView2Request, _ + ByVal Response As WebView2Response) + + ' Check if it's a specific API request + If InStr(Request.Uri, "api.example.com/track") > 0 Then + ' Add custom header + Request.Headers.AppendHeader "X-Custom-Header", "MyValue" + End If +End Sub +``` + +### 2. Request Logging + +```vb +Private Sub WebView21_WebResourceRequested(ByVal Request As WebView2Request, _ + ByVal Response As WebView2Response) + + ' Log all requests + Debug.Print "[" & Now & "] " & Request.Method & " " & Request.Uri + + ' Log specific header information + Dim referer As String + referer = Request.Headers.GetHeader("Referer") + If referer <> "" Then + Debug.Print " Referer: " & referer + End If +End Sub +``` + +### 3. Check Request in NavigationStarting + +```vb +Private Sub WebView21_NavigationStarting(ByVal Uri As String, _ + ByVal IsUserInitiated As Boolean, _ + ByVal IsRedirected As Boolean, _ + ByVal RequestHeaders As WebView2RequestHeaders, _ + ByRef Cancel As Boolean) + + ' Check request headers + If RequestHeaders.Contains("X-Block-Navigation") Then + Cancel = True + MsgBox "Navigation blocked" + End If +End Sub +``` + +## Complete Example + +```vb +Private Sub WebView21_WebResourceRequested(ByVal Request As WebView2Request, _ + ByVal Response As WebView2Response) + + ' 1. Analyze request + Debug.Print "=== WebResourceRequested ===" + Debug.Print "Method: " & Request.Method + Debug.Print "URI: " & Request.Uri + + ' 2. Iterate all request headers + Debug.Print "Headers:" + Dim header As WebView2Header + For Each header In Request.Headers + Debug.Print " " & header.Name & ": " & header.Value + Next + + ' 3. Handle specific types of requests + Select Case Request.Method + Case "POST", "PUT", "PATCH" + ' Check request body + Dim body As String + body = Request.ContentUTF8 + Debug.Print "Body: " & Left(body, 200) ' Only show first 200 characters + End Select + + ' 4. Return custom response (simulate API response) + If InStr(Request.Uri, "/api/mock-data") > 0 Then + Response.StatusCode = 200 + Response.ReasonPhrase = "OK" + Response.Headers.AppendHeader "Content-Type", "application/json" + Response.ContentUTF8 = "{\"status\":\"ok\",\"data\":[1,2,3]}" + End If +End Sub +``` + +## Notes + +1. **Thread Safety:** The `WebView2Request` object is only valid during event handling +2. **Content Modification:** Some request modifications may not affect the actual request sent, depending on WebView2 version +3. **Performance Considerations:** Frequently accessing request content may impact performance, avoid unnecessary processing +4. **Null Value Handling:** `ContentBytes` may return `Empty`, check before using diff --git a/docs/PackageReference/Webview2/WebView2RequestHeaders.md b/docs/PackageReference/Webview2/WebView2RequestHeaders.md new file mode 100644 index 0000000..d1ab40b --- /dev/null +++ b/docs/PackageReference/Webview2/WebView2RequestHeaders.md @@ -0,0 +1,205 @@ +--- +title: RequestHeaders +parent: WebView2 Package +nav_order: 12 +--- + +# WebView2RequestHeaders Class + +The `WebView2RequestHeaders` class is used to manage HTTP request header information. + +## Class Information + +| Property | Value | +| --------- | ------------------------ | +| Class Name | `WebView2RequestHeaders` | +| COM Creatable | No | + +## Methods + +### GetHeader + +```vb +Public Function GetHeader(ByVal name As String) As String +``` + +Gets the value of the request header with the specified name. + +**Parameters:** + +- `name` - Request header name + +**Return Value:** The value string of the request header + +**Example:** + +```vb +Private Sub WebView21_NavigationStarting(ByVal Uri As String, _ + ByVal IsUserInitiated As Boolean, ByVal IsRedirected As Boolean, _ + ByVal RequestHeaders As WebView2RequestHeaders, ByRef Cancel As Boolean) + + Dim userAgent As String + userAgent = RequestHeaders.GetHeader("User-Agent") + Debug.Print "User-Agent: " & userAgent +End Sub +``` + +### Contains + +```vb +Public Function Contains(ByVal name As String) As Boolean +``` + +Checks if a request header with the specified name exists. + +**Parameters:** + +- `name` - Request header name + +**Return Value:** Returns `True` if it contains, otherwise returns `False` + +**Example:** + +```vb +If RequestHeaders.Contains("Authorization") Then + Debug.Print "Request contains Authorization header" +End If +``` + +### AppendHeader + +```vb +Public Sub AppendHeader(ByVal name As String, ByVal value As String) +``` + +Sets the value of the request header (replaces if it already exists). + +**Parameters:** + +- `name` - Request header name +- `value` - Request header value + +**Example:** + +```vb +' Add custom User-Agent +RequestHeaders.AppendHeader "User-Agent", "MyApp/1.0" + +' Add Authorization header +RequestHeaders.AppendHeader "Authorization", "Bearer token123" +``` + +### RemoveHeader + +```vb +Public Sub RemoveHeader(ByVal name As String) +``` + +Removes the request header with the specified name. + +**Parameters:** + +- `name` - Request header name + +**Example:** + +```vb +RequestHeaders.RemoveHeader("Cookie") +``` + +### GetHeaders + +```vb +Public Function GetHeaders(ByVal name As String) As WebView2HeadersCollection +``` + +Gets all values of the request header with the specified name (there may be multiple headers with the same name). + +**Parameters:** + +- `name` - Request header name + +**Return Value:** `WebView2HeadersCollection` collection object + +### Enumerator + +```vb +Public Function _NewEnum() As WebView2HeadersCollection +``` + +Supports `For Each` to enumerate all request headers. + +**Example:** + +```vb +Private Sub WebView21_NavigationStarting(ByVal Uri As String, _ + ByVal IsUserInitiated As Boolean, ByVal IsRedirected As Boolean, _ + ByVal RequestHeaders As WebView2RequestHeaders, ByRef Cancel As Boolean) + + Dim header As WebView2Header + For Each header In RequestHeaders + Debug.Print header.Name & ": " & header.Value + Next +End Sub +``` + +## Usage Scenarios + +### 1. View Request Headers in Navigation Event + +```vb +Private Sub WebView21_NavigationStarting(ByVal Uri As String, _ + ByVal IsUserInitiated As Boolean, ByVal IsRedirected As Boolean, _ + ByVal RequestHeaders As WebView2RequestHeaders, ByRef Cancel As Boolean) + + Debug.Print "Navigating to: " & Uri + Debug.Print "Request headers:" + + Dim header As WebView2Header + For Each header In RequestHeaders + Debug.Print " " & header.Name & ": " & header.Value + Next +End Sub +``` + +### 2. Modify Request Headers + +```vb +Private Sub WebView21_NavigationStarting(ByVal Uri As String, _ + ByVal IsUserInitiated As Boolean, ByVal IsRedirected As Boolean, _ + ByVal RequestHeaders As WebView2RequestHeaders, ByRef Cancel As Boolean) + + ' Add custom request header + RequestHeaders.AppendHeader "X-Custom-Header", "CustomValue" + + ' Replace User-Agent + RequestHeaders.AppendHeader "User-Agent", "MyApp/2.0" +End Sub +``` + +### 3. Intercept Based on Request Headers + +```vb +Private Sub WebView21_NavigationStarting(ByVal Uri As String, _ + ByVal IsUserInitiated As Boolean, ByVal IsRedirected As Boolean, _ + ByVal RequestHeaders As WebView2RequestHeaders, ByRef Cancel As Boolean) + + ' Intercept requests missing specific authentication header + If Not RequestHeaders.Contains("Authorization") Then + Debug.Print "Missing Authorization header, cancel navigation" + Cancel = True + End If +End Sub +``` + +## Notes + +1. **Modification Timing:** Request header modifications can only be done in the `NavigationStarting` event; modifications at other times are invalid. + +2. **Case Sensitivity:** Request header names are case-insensitive, for example, "Content-Type" and "content-type" are considered the same. + +3. **Special Request Headers:** Some request headers (such as `Host`, `Content-Length`) are automatically managed by WebView2, manual modification may be invalid. + +4. **Security:** When handling sensitive information (such as `Authorization`, `Cookie`), pay attention to security to avoid leaks. + +5. **Encoding Issues:** Request header values should comply with HTTP specifications, some special characters may need encoding. diff --git a/docs/PackageReference/Webview2/WebView2Response.md b/docs/PackageReference/Webview2/WebView2Response.md new file mode 100644 index 0000000..d9eab7e --- /dev/null +++ b/docs/PackageReference/Webview2/WebView2Response.md @@ -0,0 +1,470 @@ +--- +title: Response +parent: WebView2 Package +nav_order: 11 +--- + +# WebView2Response Class + +The `WebView2Response` class is used to provide custom responses in `WebResourceRequested` event, allowing you to intercept web requests and return custom content. + +## Class Information + +| Property | Value | +| --------- | ---------------------- | +| Class Name | `WebView2Response` | +| COM Creatable | No (internal use) | +| Access Modifier | `Public` | + +## Properties + +### StatusCode + +```vb +Public Property Get StatusCode() As Long +Public Property Let StatusCode(Value As Long) +``` + +Gets or sets the HTTP response status code. + +**Complete HTTP Status Code List:** + +### 1xx Informational Responses + +| Status Code | Description | +| ---------- | ----------- | +| 100 | Continue - Client should continue its request | +| 101 | Switching Protocols | +| 102 | Processing (WebDAV) | +| 103 | Early Hints | + +### 2xx Success Responses + +| Status Code | Description | +| ---------- | ----------- | +| 200 | OK - Request successful | +| 201 | Created - Request successful and new resource created | +| 202 | Accepted - Request accepted but not yet fully processed | +| 203 | Non-Authoritative Information | +| 204 | No Content - Server successfully processed but no return content | +| 205 | Reset Content | +| 206 | Partial Content | +| 207 | Multi-Status (WebDAV) | +| 208 | Already Reported (WebDAV) | +| 226 | IM Used | + +### 3xx Redirection + +| Status Code | Description | +| ---------- | ----------- | +| 300 | Multiple Choices | +| 301 | Moved Permanently | +| 302 | Found (temporary redirect, originally "Moved Temporarily") | +| 303 | See Other | +| 304 | Not Modified - Use cached version | +| 305 | Use Proxy (deprecated) | +| 306 | (Unused) | +| 307 | Temporary Redirect - Temporary redirect (preserve request method) | +| 308 | Permanent Redirect - Permanent redirect (preserve request method) | + +### 4xx Client Error + +| Status Code | Description | +| ---------- | ----------- | +| 400 | Bad Request - Server cannot understand request | +| 401 | Unauthorized - Authentication required | +| 402 | Payment Required | +| 403 | Forbidden - Server refuses request | +| 404 | Not Found - Resource not found | +| 405 | Method Not Allowed | +| 406 | Not Acceptable | +| 407 | Proxy Authentication Required | +| 408 | Request Timeout | +| 409 | Conflict | +| 410 | Gone | +| 411 | Length Required | +| 412 | Precondition Failed | +| 413 | Payload Too Large | +| 414 | URI Too Long | +| 415 | Unsupported Media Type | +| 416 | Range Not Satisfiable | +| 417 | Expectation Failed | +| 418 | I'm a teapot (April Fool's joke) | +| 421 | Misdirected Request | +| 422 | Unprocessable Entity (WebDAV) | +| 423 | Locked (WebDAV) | +| 424 | Failed Dependency (WebDAV) | +| 425 | Too Early | +| 426 | Upgrade Required | +| 428 | Precondition Required | +| 429 | Too Many Requests | +| 431 | Request Header Fields Too Large | +| 451 | Unavailable For Legal Reasons | + +### 5xx Server Error + +| Status Code | Description | +| ---------- | ----------- | +| 500 | Internal Server Error | +| 501 | Not Implemented | +| 502 | Bad Gateway | +| 503 | Service Unavailable | +| 504 | Gateway Timeout | +| 505 | HTTP Version Not Supported | +| 506 | Variant Also Negotiates | +| 507 | Insufficient Storage (WebDAV) | +| 508 | Loop Detected (WebDAV) | +| 510 | Not Extended | +| 511 | Network Authentication Required | + +**Most Common Status Codes in WebView2:** + +| Status Code | Use Case | +| ---------- | --------- | +| **200** | Request successful, return normal content | +| **201** | Resource created successfully | +| **204** | Success but no return content (such as DELETE operation) | +| **301/302** | Redirect | +| **304** | Use cached resource | +| **400** | Request format error | +| **401** | Authentication required | +| **403** | Forbidden (can be used to block specific requests) | +| **404** | Resource doesn't exist (commonly used to intercept unwanted requests) | +| **429** | Too many requests | +| **500** | Server error | +| **502** | Gateway error | +| **503** | Service temporarily unavailable | + +**Example:** + +```vb +Private Sub WebView21_WebResourceRequested(ByVal Request As WebView2Request, _ + ByVal Response As WebView2Response) + + ' Return 404 response + If InStr(Request.Uri, "blocked.js") > 0 Then + Response.StatusCode = 404 + Response.ReasonPhrase = "Not Found" + End If +End Sub +``` + +--- + +### ReasonPhrase + +```vb +Public Property Get ReasonPhrase() As String +Public Property Let ReasonPhrase(Value As String) +``` + +Gets or sets the HTTP response reason phrase. + +**Example:** + +```vb +Response.StatusCode = 200 +Response.ReasonPhrase = "OK" +``` + +--- + +### Headers + +```vb +Public Property Get Headers() As WebView2ResponseHeaders +``` + +Gets the HTTP headers collection of the response. + +Returns [WebView2ResponseHeaders](./WebView2ResponseHeaders.md) object, used to set response headers. + +**Example:** + +```vb +Private Sub WebView21_WebResourceRequested(ByVal Request As WebView2Request, _ + ByVal Response As WebView2Response) + + ' Set JSON response headers + Response.Headers.AppendHeader "Content-Type", "application/json" + Response.Headers.AppendHeader "Cache-Control", "no-cache" +End Sub +``` + +--- + +### ContentBytes + +```vb +Public Property Get ContentBytes() As Variant +Public Property Let ContentBytes(Value As Variant) +``` + +Gets or sets the response content (byte array). + +**Description:** + +- Setting this property automatically marks response as set (`HasBeenSet = True`) +- Suitable for setting binary content (images, files, etc.) + +**Example:** + +```vb +Private Sub WebView21_WebResourceRequested(ByVal Request As WebView2Request, _ + ByVal Response As WebView2Response) + + ' Return image data + If InStr(Request.Uri, "/api/image") > 0 Then + Dim imageData() As Byte + imageData = LoadImageBytes("C:\\image.png") + + Response.StatusCode = 200 + Response.Headers.AppendHeader "Content-Type", "image/png" + Response.ContentBytes = imageData + End If +End Sub +``` + +--- + +### ContentUTF8 + +```vb +Public Property Get ContentUTF8() As String +Public Property Let ContentUTF8(ByVal Value As String) +``` + +Gets or sets the response content (UTF-8 encoded string). + +**Description:** + +- Automatically handles UTF-8 encoding +- Suitable for returning text content (HTML, JSON, XML, etc.) +- Setting this property automatically marks response as set (`HasBeenSet = True`) + +**Example:** + +```vb +Private Sub WebView21_WebResourceRequested(ByVal Request As WebView2Request, _ + ByVal Response As WebView2Response) + + ' Return JSON data + Response.StatusCode = 200 + Response.ReasonPhrase = "OK" + Response.Headers.AppendHeader "Content-Type", "application/json" + Response.ContentUTF8 = "{\"message\":\"Hello from VB!\",\"timestamp\":" & CLng(Now) & "}" +End Sub +``` + +--- + +### HasBeenSet + +```vb +Public HasBeenSet As Boolean +``` + +Indicates whether the response has been set. + +- Automatically set to `True` when setting `ContentBytes`, `ContentUTF8`, `StatusCode`, or `ReasonPhrase` +- WebView2 internally uses this property to determine whether to use custom response + +## Usage Scenarios + +### 1. Intercept and Block Specific Resources + +```vb +Private Sub WebView21_WebResourceRequested(ByVal Request As WebView2Request, _ + ByVal Response As WebView2Response) + + ' Block ad scripts + If InStr(Request.Uri, "ads.js") > 0 Or _ + InStr(Request.Uri, "tracker.js") > 0 Then + + Response.StatusCode = 404 + Response.ReasonPhrase = "Not Found" + Response.ContentUTF8 = "" + End If +End Sub +``` + +### 2. Provide Local Cached Content + +```vb +Private Sub WebView21_WebResourceRequested(ByVal Request As WebView2Request, _ + ByVal Response As WebView2Response) + + ' Intercept API requests, return local cache + If InStr(Request.Uri, "/api/data") > 0 Then + Dim cachedData As String + cachedData = GetCachedData(Request.Uri) + + If cachedData <> "" Then + Response.StatusCode = 200 + Response.Headers.AppendHeader "Content-Type", "application/json" + Response.Headers.AppendHeader "X-Cache", "HIT" + Response.ContentUTF8 = cachedData + End If + End If +End Sub +``` + +### 3. Simulate API Responses + +```vb +Private Sub WebView21_WebResourceRequested(ByVal Request As WebView2Request, _ + ByVal Response As WebView2Response) + + ' Simulate user API + If InStr(Request.Uri, "/api/user") > 0 Then + Dim jsonResponse As String + jsonResponse = "{" & _ + """id"":" & 123 & "," & _ + """name"":""张三""," & _ + """email"":""zhangsan@example.com""" & _ + "}" + + Response.StatusCode = 200 + Response.Headers.AppendHeader "Content-Type", "application/json" + Response.ContentUTF8 = jsonResponse + End If +End Sub +``` + +### 4. Modify Original Response + +```vb +Private Sub WebView21_WebResourceRequested(ByVal Request As WebView2Request, _ + ByVal Response As WebView2Response) + + ' Add custom response headers to all responses + Response.Headers.AppendHeader "X-Custom-App", "MyApp v1.0" + Response.Headers.AppendHeader "X-Processed-By", "twinBASIC WebView2" +End Sub +``` + +### 5. Return HTML Error Pages + +```vb +Private Sub WebView21_WebResourceRequested(ByVal Request As WebView2Request, _ + ByVal Response As WebView2Response) + + ' Return custom error page for certain resources + If InStr(Request.Uri, "blocked-site.com") > 0 Then + Response.StatusCode = 403 + Response.ReasonPhrase = "Forbidden" + Response.Headers.AppendHeader "Content-Type", "text/html" + Response.ContentUTF8 = _ + "" & _ + "

Access Blocked

" & _ + "

This site has been blocked by administrator.

" & _ + "" + End If +End Sub +``` + +## Complete Example + +```vb +Private Sub WebView21_WebResourceRequested(ByVal Request As WebView2Request, _ + ByVal Response As WebView2Response) + + Debug.Print "Intercepting: " & Request.Method & " " & Request.Uri + + ' Scenario 1: Intercept ads and trackers + If IsAdOrTracker(Request.Uri) Then + Response.StatusCode = 404 + Response.ReasonPhrase = "Not Found" + Exit Sub + End If + + ' Scenario 2: Provide local resources + If InStr(Request.Uri, "/local/") > 0 Then + Dim localPath As String + localPath = Replace(Request.Uri, "http://app.local/", "C:\\AppResources\\") + + If Dir(localPath) <> "" Then + ' Set Content-Type based on extension + Dim contentType As String + If Right(localPath, 4) = ".css" Then + contentType = "text/css" + ElseIf Right(localPath, 3) = ".js" Then + contentType = "application/javascript" + ElseIf Right(localPath, 4) = ".png" Then + contentType = "image/png" + Else + contentType = "application/octet-stream" + End If + + Response.StatusCode = 200 + Response.Headers.AppendHeader "Content-Type", contentType + Response.ContentBytes = ReadFileBytes(localPath) + Else + Response.StatusCode = 404 + Response.ReasonPhrase = "Not Found" + End If + Exit Sub + End If + + ' Scenario 3: API simulation + If InStr(Request.Uri, "/api/mock/") > 0 Then + HandleMockApi Request, Response + Exit Sub + End If + + ' Scenario 4: Add global response headers + Response.Headers.AppendHeader "X-App-Version", "1.0.0" +End Sub + +Private Function IsAdOrTracker(uri As String) As Boolean + ' Simple ad domain check + Dim blockedDomains As Variant + blockedDomains = Array("google-analytics.com", "doubleclick.net", "facebook.com/tr") + + Dim domain As Variant + For Each domain In blockedDomains + If InStr(uri, domain) > 0 Then + IsAdOrTracker = True + Exit Function + End If + Next + + IsAdOrTracker = False +End Function + +Private Sub HandleMockApi(Request As WebView2Request, Response As WebView2Response) + Response.StatusCode = 200 + Response.Headers.AppendHeader "Content-Type", "application/json" + + ' Return different data based on request path + If InStr(Request.Uri, "/api/mock/users") > 0 Then + Response.ContentUTF8 = "{\"users\":[{\"id\":1,\"name\":\"User1\"},{\"id\":2,\"name\":\"User2\"}]}" + ElseIf InStr(Request.Uri, "/api/mock/status") > 0 Then + Response.ContentUTF8 = "{\"status\":\"ok\",\"serverTime\":" & CLng(Now) & "}" + Else + Response.StatusCode = 404 + Response.ContentUTF8 = "{\"error\":\"API not found\"}" + End If +End Sub + +Private Function ReadFileBytes(filePath As String) As Byte() + Dim fileNum As Integer + fileNum = FreeFile + + Open filePath For Binary As #fileNum + Dim bytes() As Byte + ReDim bytes(LOF(fileNum) - 1) + Get #fileNum, , bytes + Close #fileNum + + ReadFileBytes = bytes +End Function +``` + +## Notes + +1. **Response Setting:** WebView2 will only use custom response when `HasBeenSet` is `True` +2. **Default Response:** If response is not set, WebView2 will continue sending normal network requests +3. **Content-Type:** Remember to set appropriate `Content-Type` header to ensure browser correctly parses response content +4. **Performance Impact:** Intercepting many requests may affect performance, try to set filters precisely +5. **Filter Registration:** Must use `AddWebResourceRequestedFilter` to register filters after the `Ready` event diff --git a/docs/PackageReference/Webview2/WebView2ResponseHeaders.md b/docs/PackageReference/Webview2/WebView2ResponseHeaders.md new file mode 100644 index 0000000..4fad8ca --- /dev/null +++ b/docs/PackageReference/Webview2/WebView2ResponseHeaders.md @@ -0,0 +1,297 @@ +--- +title: ResponseHeaders +parent: WebView2 Package +nav_order: 13 +--- + +# WebView2ResponseHeaders Class + +The `WebView2ResponseHeaders` class is used to manage HTTP response header information, primarily used to build custom responses in the `WebResourceRequested` event. + +## Class Information + +| Property | Value | +| --------- | -------------------------- | +| Class Name | `WebView2ResponseHeaders` | +| COM Creatable | No | + +## Methods + +### AppendHeader + +```vb +Public Sub AppendHeader(ByVal name As String, ByVal value As String) +``` + +Adds a response header (allows multiple values with the same name). + +**Parameters:** + +- `name` - Response header name +- `value` - Response header value + +**Example:** + +```vb +Private Sub WebView21_WebResourceRequested(ByVal Request As WebView2Request, _ + ByVal Response As WebView2Response) + + ' Set basic response headers + Response.Headers.AppendHeader "Content-Type", "application/json" + Response.Headers.AppendHeader "Cache-Control", "no-cache" + Response.Headers.AppendHeader "Access-Control-Allow-Origin", "*" +End Sub +``` + +### Contains + +```vb +Public Function Contains(ByVal name As String) As Boolean +``` + +Checks if a response header with the specified name exists. + +**Parameters:** + +- `name` - Response header name + +**Return Value:** Returns `True` if it contains, otherwise returns `False` + +**Example:** + +```vb +If Response.Headers.Contains("Content-Type") Then + Debug.Print "Response contains Content-Type header" +End If +``` + +### GetHeader + +```vb +Public Function GetHeader(ByVal name As String) As String +``` + +Gets the first value of the response header with the specified name. + +**Parameters:** + +- `name` - Response header name + +**Return Value:** The value string of the response header + +**Example:** + +```vb +Dim contentType As String +contentType = Response.Headers.GetHeader("Content-Type") +``` + +### GetHeaders + +```vb +Public Function GetHeaders(ByVal name As String) As WebView2HeadersCollection +``` + +Gets all values of the response header with the specified name. + +**Parameters:** + +- `name` - Response header name + +**Return Value:** `WebView2HeadersCollection` collection object + +### Enumerator + +```vb +Public Function _NewEnum() As WebView2HeadersCollection +``` + +Supports `For Each` to enumerate all response headers. + +**Example:** + +```vb +Private Sub WebView21_WebResourceRequested(ByVal Request As WebView2Request, _ + ByVal Response As WebView2Response) + + Debug.Print "Setting response headers:" + Response.Headers.AppendHeader "Content-Type", "text/html" + Response.Headers.AppendHeader "Cache-Control", "max-age=3600" + Response.Headers.AppendHeader "Server", "MyServer/1.0" + + Dim header As WebView2Header + For Each header In Response.Headers + Debug.Print " " & header.Name & ": " & header.Value + Next +End Sub +``` + +## Usage Scenarios + +### 1. Build Custom Response + +```vb +Private Sub WebView21_WebResourceRequested(ByVal Request As WebView2Request, _ + ByVal Response As WebView2Response) + + ' Set HTML response + Response.StatusCode = 200 + Response.ReasonPhrase = "OK" + Response.ContentUTF8 = "

Interception Successful

" + Response.Headers.AppendHeader "Content-Type", "text/html; charset=utf-8" + Response.Headers.AppendHeader "Content-Length", Len(Response.ContentUTF8) +End Sub +``` + +### 2. Return JSON Data + +```vb +Private Sub WebView21_WebResourceRequested(ByVal Request As WebView2Request, _ + ByVal Response As WebView2Response) + + ' Build response headers + Response.StatusCode = 200 + Response.ReasonPhrase = "OK" + Response.ContentUTF8 = "{""status"":""success"",""data"":""hello""}" + + ' Set JSON response headers + Response.Headers.AppendHeader "Content-Type", "application/json" + Response.Headers.AppendHeader "Access-Control-Allow-Origin", "*" + Response.Headers.AppendHeader "Cache-Control", "no-store" +End Sub +``` + +### 3. Intercept Image Requests + +```vb +Private Sub WebView21_WebResourceRequested(ByVal Request As WebView2Request, _ + ByVal Response As WebView2Response) + + ' Check if it's an image request + If InStr(Request.Uri, ".png") > 0 Or InStr(Request.Uri, ".jpg") > 0 Then + ' Return placeholder image + Response.StatusCode = 200 + Response.ReasonPhrase = "OK" + Response.ContentUTF8 = "" + Response.Headers.AppendHeader "Content-Type", "image/svg+xml" + End If +End Sub +``` + +### 4. Simulate API Response + +```vb +Private Sub WebView21_WebResourceRequested(ByVal Request As WebView2Request, _ + ByVal Response As WebView2Response) + + ' Intercept specific API requests + If InStr(Request.Uri, "/api/user") > 0 Then + Dim jsonData As String + jsonData = "{""id"":1,""name"":""张三"",""email"":""zhangsan@example.com""}" + + Response.StatusCode = 200 + Response.ReasonPhrase = "OK" + Response.ContentUTF8 = jsonData + + ' Set complete API response headers + Response.Headers.AppendHeader "Content-Type", "application/json" + Response.Headers.AppendHeader "Access-Control-Allow-Origin", "*" + Response.Headers.AppendHeader "Access-Control-Allow-Methods", "GET, POST, OPTIONS" + Response.Headers.AppendHeader "Access-Control-Allow-Headers", "Content-Type" + Response.Headers.AppendHeader "X-Request-ID", CStr(Timer)) + End If +End Sub +``` + +### 5. Return Error Response + +```vb +Private Sub WebView21_WebResourceRequested(ByVal Request As WebView2Request, _ + ByVal Response As WebView2Response) + + ' Intercept unauthorized access + If InStr(Request.Uri, "/admin/") > 0 Then + Dim errorHtml As String + errorHtml = "

403 Forbidden

No permission to access this resource

" + + Response.StatusCode = 403 + Response.ReasonPhrase = "Forbidden" + Response.ContentUTF8 = errorHtml + Response.Headers.AppendHeader "Content-Type", "text/html; charset=utf-8" + Response.Headers.AppendHeader "X-Error-Reason", "Unauthorized" + End If +End Sub +``` + +### 6. Set Cache Policy + +```vb +Private Sub WebView21_WebResourceRequested(ByVal Request As WebView2Request, _ + ByVal Response As WebView2Response) + + ' Set different cache policies based on resource type + If InStr(Request.Uri, ".css") > 0 Or InStr(Request.Uri, ".js") > 0 Then + ' Long-term caching for static resources + Response.Headers.AppendHeader "Cache-Control", "public, max-age=31536000" + Response.Headers.AppendHeader "Expires", "Sat, 31 Dec 2030 23:59:59 GMT" + Else + ' No caching for dynamic content + Response.Headers.AppendHeader "Cache-Control", "no-cache, no-store, must-revalidate" + Response.Headers.AppendHeader "Pragma", "no-cache" + Response.Headers.AppendHeader "Expires", "0" + End If +End Sub +``` + +## Common Response Headers + +### Content Types + +```vb +Response.Headers.AppendHeader "Content-Type", "text/html; charset=utf-8" +Response.Headers.AppendHeader "Content-Type", "application/json" +Response.Headers.AppendHeader "Content-Type", "image/jpeg" +Response.Headers.AppendHeader "Content-Type", "application/pdf" +Response.Headers.AppendHeader "Content-Type", "application/octet-stream" +``` + +### CORS Control + +```vb +Response.Headers.AppendHeader "Access-Control-Allow-Origin", "*" +Response.Headers.AppendHeader "Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS" +Response.Headers.AppendHeader "Access-Control-Allow-Headers", "Content-Type, Authorization" +``` + +### Cache Control + +```vb +Response.Headers.AppendHeader "Cache-Control", "no-cache" +Response.Headers.AppendHeader "Cache-Control", "public, max-age=3600" +Response.Headers.AppendHeader "Cache-Control", "no-store" +``` + +### Security Headers + +```vb +Response.Headers.AppendHeader "X-Content-Type-Options", "nosniff" +Response.Headers.AppendHeader "X-Frame-Options", "DENY" +Response.Headers.AppendHeader "X-XSS-Protection", "1; mode=block" +Response.Headers.AppendHeader "Strict-Transport-Security", "max-age=31536000" +``` + +## Notes + +1. **Character Encoding:** The `Content-Type` header should specify the correct character set, such as `text/html; charset=utf-8`. + +2. **CORS Issues:** For cross-origin requests, need to set the correct `Access-Control-Allow-Origin` header. + +3. **Content Length:** If setting `Content-Length` header, ensure the value matches the actual content length. + +4. **Security:** When setting custom responses, pay attention to avoid security vulnerabilities, such as XSS attacks. + +5. **Performance Considerations:** For frequently intercepted resources, ensure the response building logic is efficient to avoid blocking the main thread. + +6. **Response Integrity:** Ensure to set `StatusCode`, `ReasonPhrase`, and `Content` simultaneously, otherwise the response may be incomplete. + +7. **Special Header Handling:** Some response headers (such as `Content-Length`) may be automatically handled by WebView2, manual setting may be ignored. diff --git a/docs/PackageReference/Webview2/index.md b/docs/PackageReference/Webview2/index.md new file mode 100644 index 0000000..23dea86 --- /dev/null +++ b/docs/PackageReference/Webview2/index.md @@ -0,0 +1,130 @@ +--- +title: WebView2 Package +parent: Package Reference +nav_order: 1 +permalink: /PackageReference/Webview2/ +--- + +# WebView2 Development Documentation + +`twinBASIC`'s WebView2 package provides complete functionality for embedding Microsoft Edge WebView2 controls in Windows applications. Based on the Microsoft Edge browser kernel, it can display modern web content and interact bidirectionally with JavaScript. + +## Documentation Table of Contents + +### Overview Documents + +| Document | Description | +| ---------- | -------------------------------- | +| [Documentation Overview](./README.md) | Documentation summary and quick navigation | +| [Quick Start](./Getting-started.md) | Quick start guide | + +### Core Class References + +| Document | Description | +| ---------- | -------------------------------- | +| [WebView2 Control](./WebView2.md) | Main control class overview | +| [WebView2 Events](./WebView2-Events.md) | Detailed description of all events | +| [WebView2 Properties](./WebView2-Properties.md)| Detailed description of all properties | +| [WebView2 Methods](./WebView2-Methods.md) | Detailed description of all methods | +| [Environment Options](./WebView2EnvironmentOptions.md) | Configure WebView2 environment parameters | +| [Enumeration Types](./Enumerations.md) | All enumeration type definitions | + +### HTTP Related + +| Document | Description | +| ---------- | -------------------------------- | +| [HTTP Request](./WebView2Request.md) | Web resource request object | +| [HTTP Response](./WebView2Response.md) | Web resource response object | +| [Request Headers](./WebView2RequestHeaders.md) | HTTP request header management | +| [Response Headers](./WebView2ResponseHeaders.md)| HTTP response header management | +| [Header Collection](./WebView2HeadersCollection.md)| HTTP header collection enumeration | +| [Header Info](./WebView2Header.md) | Single HTTP header information | + +### Advanced Topics + +| Document | Description | +| ---------- | -------------------------------- | +| [Deferred Callback](./DeferredCallback.md) | Deferred event and callback mechanism | + +## Core Functionality Overview + +### 1. Web Content Display +- Load URL web pages +- Load custom HTML strings +- Support local folder virtual host mapping +- Print to PDF + +### 2. Navigation Control +- Forward/backward navigation +- Page refresh +- Custom HTTP request navigation (supports POST data, custom Headers) + +### 3. JavaScript Interaction +- Execute JavaScript code +- Synchronously call JS functions and get return values +- Asynchronously call JS functions +- Send messages to JavaScript +- Receive JavaScript messages + +### 4. Object Sharing +- Expose COM objects to JavaScript +- Support deferred invocation mode (avoid re-entrancy problems) + +### 5. Event Handling +- **Lifecycle events**: Create, Ready, Error +- **Navigation events**: NavigationStarting, NavigationComplete, SourceChanged +- **Page events**: DocumentTitleChanged, DOMContentLoaded +- **Permission events**: PermissionRequested +- **User interaction**: UserContextMenu, AcceleratorKeyPressed +- **Script dialogs**: ScriptDialogOpening +- **Resource requests**: WebResourceRequested +- **Download events**: DownloadStarting +- **New window**: NewWindowRequested +- **JavaScript communication**: JsMessage, JsAsyncResult +- **System events**: ProcessFailed, SuspendCompleted, SuspendFailed +- **Print events**: PrintToPdfCompleted, PrintToPdfFailed +- **Developer tools**: DevToolsProtocolResponse + +### 6. Advanced Features +- Developer tools +- DevTools protocol invocation +- Built-in download manager +- Task manager +- Audio control (mute, detect playback status) +- Suspend/resume (for tab management) + +## Package Structure + +``` +WebView2Package/ +├── Sources/ +│ ├── Classes/ +│ │ ├── WebView2.twin # Main control class +│ │ ├── WebView2EnvironmentOptions.twin # Environment options +│ │ ├── WebView2Request.twin # HTTP request +│ │ ├── WebView2Response.twin # HTTP response +│ │ ├── WebView2RequestHeaders.twin # Request headers +│ │ ├── WebView2ResponseHeaders.twin # Response headers +│ │ ├── WebView2HeadersCollection.twin # Header collection +│ │ ├── WebView2Header.twin # Single header info +│ │ ├── WebView2DeferredCallback.twin # Deferred callback +│ │ ├── WebView2DeferredRaiseEvent.twin # Deferred event +│ │ ├── WebView2ExecuteScriptCompleteHandler.twin # Script execution complete +│ │ └── WebView2DevToolsProtocolCallback.twin # DevTools callback +│ ├── Support/ +│ │ ├── Enumerations.twin # Enumeration definitions +│ │ ├── Types.twin # Type definitions +│ │ └── WebView2Misc.twin # Helper functions +│ └── Abstract/ # COM interface definitions +├── Resources/ # Resource files +└── Miscellaneous/ # Icons and other resources +``` + +## Dependency Requirements + +- Windows system needs **WebView2 Runtime (Evergreen)** installed +- Minimum supported WebView2 version: 86.0.616.0 + +## License + +The WebView2 package follows its own license terms, see the LICENCE.md file in the package for details. diff --git a/docs/PackageReference/index.md b/docs/PackageReference/index.md new file mode 100644 index 0000000..07f6c62 --- /dev/null +++ b/docs/PackageReference/index.md @@ -0,0 +1,15 @@ +--- +title: Package Reference +nav_order: 14 +permalink: /PackageReference/ +--- + +# Package Reference + +This section contains documentation for twinBASIC packages. + +## Available Packages + +| Package | Description | +|---------|-------------| +| [WebView2](./Webview2/) | Microsoft Edge WebView2 control for embedding web content | From 3af2a0519877a4ca46ffd121bf64ad29bc7fe2b0 Mon Sep 17 00:00:00 2001 From: woeoio Date: Tue, 17 Feb 2026 09:28:53 +0800 Subject: [PATCH 2/2] fix: Fix broken internal links in WebView2 documentation --- docs/PackageReference/Webview2/Getting-started.md | 3 +-- docs/PackageReference/Webview2/README.md | 10 +++++----- docs/PackageReference/Webview2/WebView2-Methods.md | 2 +- docs/PackageReference/Webview2/WebView2.md | 2 +- .../Webview2/WebView2EnvironmentOptions.md | 2 +- docs/PackageReference/Webview2/index.md | 2 +- 6 files changed, 10 insertions(+), 11 deletions(-) diff --git a/docs/PackageReference/Webview2/Getting-started.md b/docs/PackageReference/Webview2/Getting-started.md index 4be8e38..276990d 100644 --- a/docs/PackageReference/Webview2/Getting-started.md +++ b/docs/PackageReference/Webview2/Getting-started.md @@ -725,7 +725,6 @@ End Sub - Read [WebView2 Control](./WebView2.md) to learn all properties, methods, and events - Read [Environment Options](./WebView2EnvironmentOptions.md) to configure WebView2 environment -- Read [Enumeration Types](./Enumerations.md) to learn all enumeration values +- Read [Enumeration Types](./WebView2-Enumerations.md) to learn all enumeration values - Read [Deferred Callback](./DeferredCallback.md) to understand how to handle re-entrancy problems -- Read [Re-entrancy Issues](./Re-entrancy.md) for detailed explanation of re-entrancy problems diff --git a/docs/PackageReference/Webview2/README.md b/docs/PackageReference/Webview2/README.md index 9b37202..9b7de0d 100644 --- a/docs/PackageReference/Webview2/README.md +++ b/docs/PackageReference/Webview2/README.md @@ -39,7 +39,7 @@ twinBASIC WebView2 package provides complete Microsoft Edge WebView2 control int | Document | Description | | ------------------------------------ | ------------------------------------------- | -| [Enumeration Types](./Enumerations.md)| All enumeration type definitions and descriptions | +| [Enumeration Types](./WebView2-Enumerations.md)| All enumeration type definitions and descriptions | | [Deferred Callback](./DeferredCallback.md) | Deferred event and callback mechanism (re-entrancy issues) | ## Quick Navigation @@ -61,7 +61,7 @@ Dim result As Variant result = WebView21.JsRun("document.title") ``` -→ Refer to [WebView2 Control - JavaScript Interaction](./WebView2.md#javascript-interaction-methods) +→ Refer to [WebView2 Control - JavaScript Interaction](./WebView2.md#javascript-interaction) #### Communicate Between Twinbasic and JavaScript @@ -73,7 +73,7 @@ WebView21.PostWebMessage "Hello!" window.chrome.webview.postMessage("Hello from JS"); ``` -→ Refer to [WebView2 Control - Message Passing](./WebView2.md#message-passing-methods) +→ Refer to [WebView2 Control - Message Passing](./WebView2.md#javascript-interaction) #### Intercept HTTP Requests @@ -86,7 +86,7 @@ Private Sub WebView21_WebResourceRequested(ByVal Request As WebView2Request, _ End Sub ``` -→ Refer to [WebView2 Control - Web Resource Interception](./WebView2.md#web-resource-interception-methods) +→ Refer to [WebView2 Control - Web Resource Interception](./WebView2.md#resource-management) #### Customize Right-Click Menu @@ -104,7 +104,7 @@ End Sub WebView21.PrintToPdf "C:\output.pdf" ``` -→ Refer to [WebView2 Control - Advanced Features](./WebView2.md#advanced-features-methods) +→ Refer to [WebView2 Control - Advanced Features](./WebView2.md#advanced-features) #### Configure Environment Options diff --git a/docs/PackageReference/Webview2/WebView2-Methods.md b/docs/PackageReference/Webview2/WebView2-Methods.md index 2a054f8..2adbc10 100644 --- a/docs/PackageReference/Webview2/WebView2-Methods.md +++ b/docs/PackageReference/Webview2/WebView2-Methods.md @@ -198,7 +198,7 @@ Public Sub AddObject(ByVal ObjName As String, ByVal Object As Object, ByVal UseD | `False` | Direct invocation, can return values to JavaScript, but may cause reentrancy issues | | `True` | Deferred invocation, avoids reentrancy issues, returns values to JavaScript via Promise asynchronously | -See [Deferred Callback Mechanism](./DeferredCallback.md#addobject-deferred-invocation) for detailed comparison and use cases of both modes. +See [Deferred Callback Mechanism](./DeferredCallback.md#deferred-invocation-for-addobject) for detailed comparison and use cases of both modes. **Example:** diff --git a/docs/PackageReference/Webview2/WebView2.md b/docs/PackageReference/Webview2/WebView2.md index 4923797..61aae38 100644 --- a/docs/PackageReference/Webview2/WebView2.md +++ b/docs/PackageReference/Webview2/WebView2.md @@ -319,7 +319,7 @@ End Sub - [WebView2 Properties Detailed Documentation](./WebView2-Properties.md) - [WebView2 Methods Detailed Documentation](./WebView2-Methods.md) - [WebView2 Environment Options](./WebView2EnvironmentOptions.md) -- [Enumeration Types](./Enumerations.md) +- [Enumeration Types](./WebView2-Enumerations.md) - [Deferred Callback Mechanism](./DeferredCallback.md) - [Quick Start Guide](./Getting-started.md) diff --git a/docs/PackageReference/Webview2/WebView2EnvironmentOptions.md b/docs/PackageReference/Webview2/WebView2EnvironmentOptions.md index ce4740d..d447a87 100644 --- a/docs/PackageReference/Webview2/WebView2EnvironmentOptions.md +++ b/docs/PackageReference/Webview2/WebView2EnvironmentOptions.md @@ -71,7 +71,7 @@ End Sub - Place user data folder in application data directory - Use independent subfolder for each instance to avoid locking issues -- Refer to [Customize the UserDataFolder](./Customize-the-UserDataFolder.md) for more information +- Ensure the folder path is not too long, otherwise creation may fail --- diff --git a/docs/PackageReference/Webview2/index.md b/docs/PackageReference/Webview2/index.md index 23dea86..326ddd4 100644 --- a/docs/PackageReference/Webview2/index.md +++ b/docs/PackageReference/Webview2/index.md @@ -27,7 +27,7 @@ permalink: /PackageReference/Webview2/ | [WebView2 Properties](./WebView2-Properties.md)| Detailed description of all properties | | [WebView2 Methods](./WebView2-Methods.md) | Detailed description of all methods | | [Environment Options](./WebView2EnvironmentOptions.md) | Configure WebView2 environment parameters | -| [Enumeration Types](./Enumerations.md) | All enumeration type definitions | +| [Enumeration Types](./WebView2-Enumerations.md) | All enumeration type definitions | ### HTTP Related