### Install NuGet Package Locally Source: https://github.com/microsoftedge/webview2samples/blob/main/SampleApps/WebView2APISample/documentation/Testing-Instructions.md Command to install a local NuGet package for the WebView2APISample project. Ensure the correct package file path is provided. ```powershell Install-Package ``` -------------------------------- ### Setup and Event Listeners for Drag and Drop Source: https://github.com/microsoftedge/webview2samples/blob/main/SampleApps/WebView2APISample/assets/ScenarioDragDropOverride.html This JavaScript code sets up the initial image element for dragging and attaches event listeners for drop and dragover events to designated containers. It also includes functions to handle drag start and drop operations. ```javascript window.addEventListener("DOMContentLoaded", () => { let img = document.createElement('img'); img.id = 'drag1'; img.src = 'EdgeWebView2-80.jpg'; img.width = 240; img.height = 240; img.draggable = true; img.addEventListener('dragstart', imgDrag); document.getElementById('div2').appendChild(img); let containers = document.querySelectorAll('.imgcontainer'); for (container of containers) { container.addEventListener('drop', onDrop); container.addEventListener('dragover', allowDrop); } }); function allowDrop(ev) { // The dragover event prevents drop events by default so we disable // the default behavior. ev.preventDefault(); } function imgDrag(ev) { ev.dataTransfer.setData("text", ev.target.id); } function onDrop(ev) { ev.preventDefault(); var data = ev.dataTransfer.getData("text"); ev.target.appendChild(document.getElementById(data)); } ``` -------------------------------- ### Set Property Value Source: https://github.com/microsoftedge/webview2samples/blob/main/SampleApps/WebView2WindowsFormsBrowser/assets/hostObject.html Demonstrates setting a property value on the host object. A prompt is used to get the new value. ```javascript document.getElementById('propertySet').addEventListener('click', async () => { const bridge = chrome.webview.hostObjects.bridge; bridge.Prop = prompt('Property text', 'Property text'); }); ``` -------------------------------- ### Initial Setup and Registration Calls Source: https://github.com/microsoftedge/webview2samples/blob/main/SampleApps/WebView2APISample/assets/ScenarioServiceWorkerSyncRegistrationManager.html Initializes permission checks, registers the service worker, and fetches existing sync registrations for both periodic and background sync types upon page load. ```javascript checkPermission(); registerServiceWorker(); getSyncRegistrations("periodic-sync"); getSyncRegistrations("background-sync"); ``` -------------------------------- ### Set Item by Index Source: https://github.com/microsoftedge/webview2samples/blob/main/SampleApps/WebView2WindowsFormsBrowser/assets/hostObject.html Shows how to set an item in the host object using an indexer. A prompt is used to get the new value. ```javascript document.getElementById('indexerSet').addEventListener('click', async () => { const bridge = chrome.webview.hostObjects.bridge; bridge[1] = prompt('Property text', 'Property text'); }); ``` -------------------------------- ### Get Item by Index Source: https://github.com/microsoftedge/webview2samples/blob/main/SampleApps/WebView2WindowsFormsBrowser/assets/hostObject.html Illustrates retrieving an item from the host object using an indexer. The retrieved item is displayed in an alert. ```javascript document.getElementById('indexerGet').addEventListener('click', async () => { const bridge = chrome.webview.hostObjects.bridge; const result = await bridge[1]; alert(result); }); ``` -------------------------------- ### WebView Script Debugging Example Source: https://github.com/microsoftedge/webview2samples/blob/main/SampleApps/WebView2APISample/assets/ScenarioJavaScriptDebugIndex.html This snippet demonstrates basic console logging within a WebView. Ensure the WebView is configured for script debugging to see these logs. ```javascript console.log("This is the very first line of code that executes."); console.log("Second"); console.log("Third"); ``` ```javascript console.log("End"); ``` -------------------------------- ### Get Item by Alias Index Source: https://github.com/microsoftedge/webview2samples/blob/main/SampleApps/WebView2WindowsFormsBrowser/assets/hostObject.html Demonstrates retrieving an item from the host object using an alias and an indexer. The retrieved item is displayed in an alert. ```javascript document.getElementById('indexerGetAlias').addEventListener('click', async () => { const bridge = chrome.webview.hostObjects.bridge; const result = await bridge.Items[12]; alert(result); }); ``` -------------------------------- ### Get Property Async Source: https://github.com/microsoftedge/webview2samples/blob/main/SampleApps/WebView2APISample/assets/ScenarioAddHostObject.html Use this to asynchronously retrieve the value of a property from the host object. No special setup is required beyond the host object being available. ```javascript const propertyValue = await chrome.webview.hostObjects.sample.property; ``` -------------------------------- ### Inject JavaScript and Get Result Source: https://github.com/microsoftedge/webview2samples/blob/main/SampleApps/WebView2APISample/documentation/Testing-Instructions.md Executes JavaScript code and retrieves the result. This example shows how to handle potential errors during script execution and get string results. Use 'ExecuteScriptWithResultAsync' for asynchronous operations. ```csharp "abc" ``` -------------------------------- ### Get Property Value Source: https://github.com/microsoftedge/webview2samples/blob/main/SampleApps/WebView2WindowsFormsBrowser/assets/hostObject.html Shows how to retrieve the value of a property from the host object. The retrieved value is displayed in an alert. ```javascript document.getElementById('propertyGet').addEventListener('click', async () => { const bridge = chrome.webview.hostObjects.bridge; const result = await bridge.Prop; alert(result); }); ``` -------------------------------- ### Set Item by Alias Index Source: https://github.com/microsoftedge/webview2samples/blob/main/SampleApps/WebView2WindowsFormsBrowser/assets/hostObject.html Illustrates setting an item in the host object using an alias and an indexer. A prompt is used to get the new value. ```javascript document.getElementById('indexerSetAlias').addEventListener('click', async () => { const bridge = chrome.webview.hostObjects.bridge; bridge.Items[12] = prompt('Property text', 'Property text'); }); ``` -------------------------------- ### Initialize and Gather ICE Candidates Source: https://github.com/microsoftedge/webview2samples/blob/main/SampleApps/WebView2APISample/assets/ScenarioWebrtcUdpPortConfiguration.html This JavaScript code initializes an RTCPeerConnection with STUN servers and starts the ICE candidate gathering process. It handles the 'onicecandidate' and 'onicegatheringstatechange' events to display progress and final results. A data channel is created to trigger the gathering. ```javascript let peerConnection = null; let candidates = []; function showStatus(message, isError = false) { const statusDiv = document.getElementById('status'); const errorDiv = document.getElementById('error'); if (isError) { errorDiv.textContent = message; errorDiv.style.display = 'block'; statusDiv.style.display = 'none'; } else { statusDiv.textContent = message; statusDiv.style.display = 'block'; errorDiv.style.display = 'none'; } } function updateStats() { const stats = { total: candidates.length, host: candidates.filter(c => c.type === 'host').length, srflx: candidates.filter(c => c.type === 'srflx').length, relay: candidates.filter(c => c.type === 'relay').length }; document.getElementById('totalCandidates').textContent = stats.total; document.getElementById('hostCandidates').textContent = stats.host; document.getElementById('srflxCandidates').textContent = stats.srflx; document.getElementById('relayCandidates').textContent = stats.relay; } function parseCandidate(candidateString) { const parts = candidateString.split(' '); const candidate = {}; if (parts.length >= 8) { candidate.foundation = parts[0].replace('candidate:', ''); candidate.component = parts[1]; candidate.protocol = parts[2]; candidate.priority = parseInt(parts[3]); candidate.address = parts[4]; candidate.port = parseInt(parts[5]); candidate.type = parts[7]; // typ host/srflx/relay // Extract additional attributes for (let i = 8; i < parts.length; i += 2) { if (parts[i] && parts[i + 1]) { candidate[parts[i]] = parts[i + 1]; } } } return candidate; } function addCandidateToTable(candidate, candidateString) { const tbody = document.getElementById('candidatesBody'); const row = tbody.insertRow(); // Determine row class based on candidate type let rowClass = ''; if (candidate.type === 'host') { rowClass = 'host-candidate'; } else if (candidate.type === 'srflx') { rowClass = 'srflx-candidate'; } else if (candidate.type === 'relay') { rowClass = 'relay-candidate'; } row.className = rowClass; row.insertCell(0).textContent = candidate.type || 'unknown'; row.insertCell(1).textContent = candidate.protocol || 'unknown'; row.insertCell(2).textContent = candidate.address || 'unknown'; row.insertCell(3).textContent = candidate.port || 'unknown'; row.insertCell(4).textContent = candidate.foundation || 'unknown'; row.insertCell(5).textContent = candidate.priority || 'unknown'; row.insertCell(6).textContent = candidateString; } async function startGathering() { try { showStatus('Starting ICE candidate gathering...'); // Clear previous results candidates = []; document.getElementById('candidatesBody').innerHTML = ''; // Enable/disable buttons document.getElementById('startBtn').disabled = true; // Create RTCPeerConnection with ICE servers const configuration = { iceServers: [ { urls: 'stun:stun.l.google.com:19302' }, { urls: 'stun:stun1.l.google.com:19302' }, { urls: 'stun:stun2.l.google.com:19302' } ], iceCandidatePoolSize: 10 }; peerConnection = new RTCPeerConnection(configuration); // Set up event handlers peerConnection.onicecandidate = (event) => { if (event.candidate) { const candidateString = event.candidate.candidate; const parsed = parseCandidate(candidateString); candidates.push(parsed); addCandidateToTable(parsed, candidateString); updateStats(); // Update status to show progress if (peerConnection.iceGatheringState === 'gathering') { showStatus(`ICE gathering in progress... Found ${candidates.length} candidates so far.`); } } else { setTimeout(() => { if (peerConnection && peerConnection.iceGatheringState === 'complete') { showStatus(`ICE gathering complete! Found ${candidates.length} candidates.`); document.getElementById('startBtn').disabled = false; } }, 100); } }; peerConnection.onicegatheringstatechange = () => { if (peerConnection.iceGatheringState === 'gathering') { showStatus('ICE gathering in progress...'); } else if (peerConnection.iceGatheringState === 'complete') { showStatus(`ICE gathering complete! Found ${candidates.length} candidates.`); document.getElementById('startBtn').disabled = false; } }; // Create a data channel to trigger ICE gathering const dataChannel = peerConnection.createDataChannel('test', { ordered: true }); // Create offer to start ICE gathering const offer = await peerConnection.createOffer(); await peerConnection.setLocalDescription(offer); showStatus('ICE gathering in progress...'); // Add a safety timeout in case gathering gets stuck setTimeout(() => { if (peerConnection && peerConnection.iceGatheringState !== 'complete') { showStatus(`ICE gathering timeout. Found ${candidates.length} candidates. You can try again.`); document.getElementById('startBtn').disabled = false; } }, 5000); // 5 second safety timeout } catch (error) { showStatus(`Error: ${error.message}`, true); document.getElementById('startBtn').disabled = false; } } function clearResults() { candidates = []; document.getElement ``` -------------------------------- ### Get Host Object Indexer Source: https://github.com/microsoftedge/webview2samples/blob/main/SampleApps/WebView2WpfBrowser/assets/hostObject.html Retrieves a value from a host object's indexer. Displays the result in an alert. ```javascript document.getElementById('indexerGet').addEventListener('click', async () => { const bridge = chrome.webview.hostObjects.bridge; const result = await bridge[1]; alert(result); }); ``` -------------------------------- ### Get Property Value Source: https://github.com/microsoftedge/webview2samples/blob/main/SampleApps/WebView2WpfBrowser/assets/hostObject.html Retrieves the value of a property from a host object. The retrieved value is then displayed using an alert. ```javascript document.getElementById('propertyGet').addEventListener('click', async () => { const bridge = chrome.webview.hostObjects.bridge; const result = await bridge.Prop; alert(result); }) ``` -------------------------------- ### Get Host Object Indexer with Alias Source: https://github.com/microsoftedge/webview2samples/blob/main/SampleApps/WebView2WpfBrowser/assets/hostObject.html Retrieves a value from a host object's indexer using an alias. Displays the result in an alert. ```javascript document.getElementById('indexerGetAlias').addEventListener('click', async () => { const bridge = chrome.webview.hostObjects.bridge; const result = await bridge.Items[12]; alert(result); }); ``` -------------------------------- ### Inject JavaScript into WebView Source: https://github.com/microsoftedge/webview2samples/blob/main/SampleApps/WebView2APISample/documentation/Testing-Instructions.md Executes JavaScript code within the WebView. This example demonstrates a simple confirmation dialog. Use 'ExecuteScriptAsync' for asynchronous execution. ```csharp confirm("Confirm?") ``` -------------------------------- ### Get Property Sync Source: https://github.com/microsoftedge/webview2samples/blob/main/SampleApps/WebView2APISample/assets/ScenarioAddHostObject.html Use this to synchronously retrieve the value of a property from the host object. Ensure the 'sync' namespace is available for synchronous operations. ```javascript const propertyValue = chrome.webview.hostObjects.sync.sample.property; ``` -------------------------------- ### Add a Sensitivity Label Source: https://github.com/microsoftedge/webview2samples/blob/main/SampleApps/WebView2APISample/assets/ScenarioSensitivityLabelChanged.html Use this code to add a sensitivity label to the WebView. Ensure you have the correct label and organization GUIDs. ```javascript const labelManager = await navigator.pageInteractionRestrictionManager.requestLabelManager(); const label = await labelManager.addLabel('MicrosoftSensitivityLabel', { label: 'your-label-guid', organization: 'your-org-guid' }); ``` -------------------------------- ### Get Periodic or Background Sync Registrations Source: https://github.com/microsoftedge/webview2samples/blob/main/SampleApps/WebView2APISample/assets/ScenarioServiceWorkerSyncRegistrationManager.html Retrieves and displays the tags for all registered periodic or background sync tasks. Updates the corresponding DOM element with the registration information. ```javascript async function getSyncRegistrations(type) { const registration = await navigator.serviceWorker.ready; let elementId = "periodic-sync-registrations"; let tags; if (type === "background-sync") { elementId = "background-sync-registrations"; tags = await registration.sync.getTags(); } else if (type === "periodic-sync") { tags = await registration.periodicSync.getTags(); } var registrations = ""; tags.forEach(tag => { registrations += "Tag name: "; registrations += tag; registrations += " "; }); if (registrations === "") { registrations = "empty"; } document.getElementById(elementId).textContent = registrations; } ``` -------------------------------- ### DOMContentLoaded Event Listener Source: https://github.com/microsoftedge/webview2samples/blob/main/SampleApps/webview2_sample_uwp/Html/add_host_object.html Attaches the Initialize function to the 'DOMContentLoaded' event, ensuring that the host object setup occurs after the HTML document has been fully loaded and parsed. ```javascript document.addEventListener("DOMContentLoaded", Initialize); ``` -------------------------------- ### Get Indexed Property Async Source: https://github.com/microsoftedge/webview2samples/blob/main/SampleApps/WebView2APISample/assets/ScenarioAddHostObject.html Retrieve a property from the host object using an index asynchronously. The index is provided as a parameter within square brackets. ```javascript await chrome.webview.hostObjects.sample.indexedProperty[paramValue] ``` -------------------------------- ### Event Listener for Get Property Async Source: https://github.com/microsoftedge/webview2samples/blob/main/SampleApps/WebView2APISample/assets/ScenarioAddHostObject.html Attaches an event listener to a button that, when clicked, retrieves a property asynchronously from the host object and displays it in a designated output element. ```javascript document.getElementById("getPropertyAsyncButton").addEventListener("click", async () => { const propertyValue = await chrome.webview.hostObjects.sample.property; document.getElementById("getPropertyAsyncOutput").textContent = propertyValue; }); ``` -------------------------------- ### Event Listener for Get Property Sync Source: https://github.com/microsoftedge/webview2samples/blob/main/SampleApps/WebView2APISample/assets/ScenarioAddHostObject.html Attaches an event listener to a button that, when clicked, synchronously retrieves a property from the host object and displays it in a designated output element. ```javascript document.getElementById("getPropertySyncButton").addEventListener("click", () => { const propertyValue = chrome.webview.hostObjects.sync.sample.property; document.getElementById("getPropertySyncOutput").textContent = propertyValue; }); ``` -------------------------------- ### Handle File Selection and Display Source: https://github.com/microsoftedge/webview2samples/blob/main/SampleApps/WebView2APISample/assets/ScenarioDragDrop.html Sets up an event listener for file input changes, displays the chosen files, and sends them to the host application. ```javascript function setFilePath() { const curFiles = input.files; preview.innerHTML = ""; if (curFiles.length === 0) { const para = document.createElement('p'); para.textContent = 'No files currently selected for upload'; preview.appendChild(para); } else { const para = document.createElement('p'); para.textContent = 'Chosen files:'; preview.appendChild(para); const list = document.createElement('ol'); preview.appendChild(list); chrome.webview.addEventListener("message", function (e) { for (var fileKey in e.data) { const listItem = document.createElement('li'); const para = document.createElement('p'); var file = e.data[fileKey]; para.textContent = `${file.path}`; listItem.appendChild(para); list.appendChild(listItem); } }); // Note that postMessageWithAdditionalObjects does not accept a single object, // but only accepts an ArrayLike object. // However, input.files is type FileList, which is already an ArrayLike object so // no conversion to array is needed. chrome.webview.postMessageWithAdditionalObjects("FilesDropped", curFiles); } } const input = document.getElementById('files'); input.addEventListener('change', setFilePath); ``` -------------------------------- ### Initialize UI Elements and IFrame Source: https://github.com/microsoftedge/webview2samples/blob/main/SampleApps/WebView2APISample/assets/ScenarioWebMessage.html Sets up the initial state of the page, including dynamic content for class names, menu items, and descriptions based on whether the page is top-level or an iframe. Also initiates iframe creation. ```javascript window.onload = function () { var class_value; var menu_item; var description; if (window.top === window) { var div_summary = document.getElementById("div_summary"); div_summary.style.display = 'block'; createIFrame(); class_value = "ICoreWebView2"; menu_item = "Post Message JSON"; description = "page"; } else { class_value = "ICoreWebView2Frame"; menu_item = "Post Message JSON IFrame"; description = "iframe"; } document.getElementById("class1").innerHTML = class_value; document.getElementById("class2").innerHTML = class_value; document.getElementById("class3").innerHTML = class_value; document.getElementById("menu").innerHTML = menu_item; document.getElementById("page").innerHTML = description; }; ``` -------------------------------- ### Initialize Host Object and Event Listener Source: https://github.com/microsoftedge/webview2samples/blob/main/SampleApps/webview2_sample_uwp/Html/add_host_object.html Sets up the default synchronous proxy for host objects and adds an event listener for 'itemsChangedEvent'. This code should be run when the web view is ready. ```javascript function Initialize() { chrome.webview.hostObjects.options.defaultSyncProxy = true; bridgeInstance = chrome.webview.hostObjects.sync.BridgeInstance; bridgeInstance.addEventListener("itemsChangedEvent", UpdateItemsListView); document.getElementById("StringPropertySpan").innerHTML = bridgeInstance.stringProperty; } ``` -------------------------------- ### Initialize WebView2 Content and UI Elements Source: https://github.com/microsoftedge/webview2samples/blob/main/SampleApps/WebView2WindowsFormsBrowser/assets/webMessages.html Sets up the initial state of the page, including dynamically setting UI text based on whether the WebView is the top-level window or an iframe. Calls createIFrame to load content. ```javascript window.onload = function () { var class_value; var menu_item; var description; if (window.top === window) { var div_summary = document.getElementById("div_summary"); div_summary.style.display = 'block'; createIFrame(); class_value = "ICoreWebView2"; menu_item = "Post Message JSON"; description = "page"; } else { class_value = "ICoreWebView2Frame"; menu_item = "IFrame Post Message JSON"; description = "iframe"; } document.getElementById("class1").innerHTML = class_value; document.getElementById("class2").innerHTML = class_value; document.getElementById("class3").innerHTML = class_value; document.getElementById("menu").innerHTML = menu_item; document.getElementById("page").innerHTML = description; }; ``` -------------------------------- ### Call Async Method with Parameters Source: https://github.com/microsoftedge/webview2samples/blob/main/SampleApps/WebView2WindowsFormsBrowser/assets/hostObject.html Demonstrates calling an asynchronous method on the host object that accepts parameters. The result is displayed in an alert. ```javascript document.getElementById('methodWithParam').addEventListener('click', async () => { const bridge = chrome.webview.hostObjects.bridge; const result = await bridge.TaskVoid(prompt('How many milliseconds should the async operation take? Enter zero or less to make it return immediately and synchronously.', '2000')); alert(result); }); ``` -------------------------------- ### Call Method with No Parameters Source: https://github.com/microsoftedge/webview2samples/blob/main/SampleApps/WebView2WindowsFormsBrowser/assets/hostObject.html Shows how to call a synchronous method on the host object that does not require any parameters. The result is displayed in an alert. ```javascript document.getElementById('methodNoParam').addEventListener('click', async () => { const bridge = chrome.webview.hostObjects.bridge; const result = await bridge.Func2(); alert(result); }); ``` -------------------------------- ### Get Element Bounding Rect Source: https://github.com/microsoftedge/webview2samples/blob/main/SampleApps/webview2_sample_uwp/Html/popups_and_dialogs.html Retrieves the bounding rectangle of an HTML element by its ID. This can be useful for positioning or sizing overlays. ```javascript function getElementBoundingClientRect(id) { return document.getElementById(id).getBoundingClientRect().toJSON(); } ``` -------------------------------- ### Get Indexed Property Asynchronously Source: https://github.com/microsoftedge/webview2samples/blob/main/SampleApps/WebView2APISample/assets/ScenarioAddHostObject.html Retrieve a property from a host object using an index asynchronously. This is useful for collections or indexed data. ```javascript const index = parseInt(document.getElementById("getIndexedPropertyAsyncParam").value); const resultValue = await chrome.webview.hostObjects.sample.IndexedProperty[index]; document.getElementById("getIndexedPropertyAsyncOutput").textContent = resultValue; ``` -------------------------------- ### Get Geolocation Position Source: https://github.com/microsoftedge/webview2samples/blob/main/SampleApps/WebView2APISample/assets/ScenarioIFrameDevicePermissionIFrame.html Call this function to request the user's current geolocation. It uses the browser's Geolocation API. ```javascript function testLocation() { navigator.geolocation.getCurrentPosition(showPosition); } ``` ```javascript function showPosition(position) { document.getElementById("locationResult").innerHTML = "Location Result: " + position.coords.latitude + " " + position.coords.longitude; } ``` -------------------------------- ### Render File Explorer Source: https://github.com/microsoftedge/webview2samples/blob/main/SampleApps/WebView2APISample/assets/ScenarioFileSystemHandleShare.html Renders the file explorer UI by creating the root list item and appending it to the file tree element. It also sets up event listeners for browsing the root directory. ```javascript function renderFileExplorer(fileSystemHandle) { var fileExplorer = document.getElementById("file-explorer"); var fileTree = document.getElementById("file-tree"); fileTree.innerHTML = ""; var root = createListItem(fileSystemHandle); root.classList.add("directory"); fileTree.appendChild(root); root.id = "root"; } ``` -------------------------------- ### Run All Host Object Tests Source: https://github.com/microsoftedge/webview2samples/blob/main/SampleApps/WebView2WpfBrowser/assets/hostObject.html Executes a comprehensive suite of tests for interacting with host objects. This includes testing property get/set, method calls with and without parameters, asynchronous operations, indexed access, and object type verification. ```javascript document.getElementById('runTest').addEventListener('click', async () => { const bridge = chrome.webview.hostObjects.bridge; let expected_result = 'value1'; bridge.Prop = expected_result; let result = await bridge.Prop; assertEqual(result, expected_result, 'property on bridge'); const value2 = 'value2'; result = await bridge.Func(value2); expected_result = 'BridgeAddRemoteObject.Func(' + value2 + ')'; assertEqual(result, expected_result, 'method with parameter'); result = await bridge.Func2(); expected_result = 'BridgeAddRemoteObject.Func2()'; assertEqual(result, expected_result, 'method with no parameter'); result = await bridge.FuncAsync(500); expected_result = 'BridgeAddRemoteObject.FuncAsync(500)'; assertEqual(result, expected_result, 'async method with parameter'); result = await bridge.Func2Async(); expected_result = 'BridgeAddRemoteObject.Func2Async()'; assertEqual(result, expected_result, 'async method with no parameter'); result = await bridge.FuncAsync(0); expected_result = 'BridgeAddRemoteObject.FuncAsync(0)'; assertEqual(result, expected_result, 'async method with no delay'); const another_object = bridge.AnotherObject; another_object.Prop = value2; result = await another_object.Prop; expected_result = value2; assertEqual(result, expected_result, 'property on another_object'); chrome.webview.hostObjects.options.shouldSerializeDates = true; const date = new Date(); bridge.DateProp = date; const date2 = await bridge.DateProp; assertEqual(date2.getTime(), date.getTime(), 'test date object serialization'); let index = 123; expected_result = 'aa'; bridge[index] = expected_result; result = await bridge[index]; assertEqual(result, expected_result, 'bridge[index]'); index = 321; expected_result = 'bb'; bridge.Items[index] = expected_result; result = await bridge.Items[index]; assertEqual(result, expected_result, 'bridge.Items[index]'); let resolved_bridge = await bridge; result = await bridge.GetObjectType(resolved_bridge); expected_result = 'BridgeAddRemoteObject'; assertEqual(result, expected_result, 'type of resolved_bridge'); result = await bridge.GetObjectType(bridge); expected_result = 'BridgeAddRemoteObject'; assertEqual(result, expected_result, 'type of bridge'); result = await bridge.GetObjectType(another_object); expected_result = 'AnotherRemoteObject'; assertEqual(result, expected_result, 'type of another_object'); result = await bridge.GetObjectTypeAsync(another_object); expected_result = 'AnotherRemoteObject'; assertEqual(result, expected_result, 'type of another_object asynchronously'); alert('Test End'); }); ``` -------------------------------- ### Initialize File Explorer on DOM Load Source: https://github.com/microsoftedge/webview2samples/blob/main/SampleApps/WebView2APISample/assets/ScenarioFileSystemHandleShare.html Sets up an event listener for the 'DOMContentLoaded' event to initialize the file explorer when the DOM is ready. It adds a click listener to the 'browse-root' element to allow users to select a directory. ```javascript document.addEventListener("DOMContentLoaded", function () { var browseRoot = document.getElementById("browse-root"); browseRoot.addEventListener("click", async function () { var dirHandle = await window.showDirectoryPicker(); renderFileExplorer(dirHandle); }); }); ``` -------------------------------- ### Call Host Object Method with Parameter Source: https://github.com/microsoftedge/webview2samples/blob/main/SampleApps/WebView2WindowsFormsBrowser/assets/hostObject.html Invokes a host object method that accepts a string parameter. Prompts the user for input to be passed as the argument. ```javascript document.getElementById('method').addEventListener('click', async () => { const bridge = chrome.webview.hostObjects.bridge; const result = await bridge.Func(prompt('Method parameter text', 'Method parameter text')); alert(result); }); ``` -------------------------------- ### Enable Browser Accelerators Source: https://github.com/microsoftedge/webview2samples/blob/main/SampleApps/WebView2APISample/assets/ScenarioAcceleratorKeyPressed.html Use this function to enable all browser accelerator keys. This function sends a message to the WebView2 control to enable accelerators. ```javascript function EnableBrowserAccelerators() { window.chrome.webview.postMessage("EnableBrowserAccelerators"); } ``` -------------------------------- ### Create File Explorer List Item Source: https://github.com/microsoftedge/webview2samples/blob/main/SampleApps/WebView2APISample/assets/ScenarioFileSystemHandleShare.html Creates a list item element for a given FileSystemHandle. Handles click events to expand directories or open files. ```javascript function createListItem(handle) { var li = document.createElement("li"); li.textContent = handle.name; li.addEventListener("click", async function (e) { e.stopPropagation(); if (handle.kind === "directory") { li.classList.toggle("expanded"); if (li.classList.contains("expanded")) { var entries = handle.values(); for await (var entry of entries) { var child = createListItem(entry); child.classList.add(entry.kind); li.appendChild(child); } } else { // Remove all children except the first one while (li.childNodes.length > 1) { li.removeChild(li.lastChild); } } } else { // If it is a file, open it in a new window // Get a file object from the handle var file = await handle.getFile(); // Create a URL from the file object var url = URL.createObjectURL(file); window.open(url); } }); return li; } ``` -------------------------------- ### Handle Incoming Messages - JavaScript Source: https://github.com/microsoftedge/webview2samples/blob/main/SampleApps/WebView2APISample/assets/ScenarioPermissionManagement.html Listens for messages from the WebView2 host. If a message contains 'PermissionSetting', it adds the setting to the list. ```javascript chrome.webview.addEventListener("message", args => { if ("PermissionSetting" in args.data) { addItem(args.data.PermissionSetting); } }); ``` -------------------------------- ### Set Host Object Property Source: https://github.com/microsoftedge/webview2samples/blob/main/SampleApps/WebView2WpfBrowser/assets/hostObject.html Sets a property on the host object. Prompts the user for input. ```javascript document.getElementById('propertySet').addEventListener('click', async () => { const bridge = chrome.webview.hostObjects.bridge; bridge.Prop = prompt('Property text', 'Property text'); }); ``` -------------------------------- ### Call Async Method with No Parameters Source: https://github.com/microsoftedge/webview2samples/blob/main/SampleApps/WebView2WindowsFormsBrowser/assets/hostObject.html Demonstrates calling an asynchronous method on the host object that does not require parameters. The result is displayed in an alert. ```javascript document.getElementById('methodNoParamAsync').addEventListener('click', async () => { const bridge = chrome.webview.hostObjects.bridge; const result = await bridge.Func2Async(); alert(result); }); ``` -------------------------------- ### Test Screen Capture Functionality Source: https://github.com/microsoftedge/webview2samples/blob/main/SampleApps/WebView2APISample/ScenarioScreenCaptureIFrame2.html This JavaScript function initiates the screen capture process. It should be called when testing the screen capture feature. ```javascript function testScreenCapture() { navigator.mediaDevices.getDisplayMedia(); } ``` -------------------------------- ### JavaScript Cookie Management Functions Source: https://github.com/microsoftedge/webview2samples/blob/main/SampleApps/WebView2APISample/assets/ScenarioCookieManagement.html These JavaScript functions handle user interactions for cookie management operations like getting, adding/updating, and deleting cookies by posting messages to the WebView. ```javascript function GetCookies() { let uri = document.getElementById("getCookiesParam1"); window.chrome.webview.postMessage(`GetCookies ${uri.value}`); } ``` ```javascript function AddOrUpdateCookie() { window.chrome.webview.postMessage(`AddOrUpdateCookie`); } ``` ```javascript function DeleteAllCookies() { window.chrome.webview.postMessage(`DeleteAllCookies`); } ``` -------------------------------- ### Invoke Method Async Source: https://github.com/microsoftedge/webview2samples/blob/main/SampleApps/WebView2APISample/assets/ScenarioAddHostObject.html Asynchronously call a method on the host object, passing parameters and awaiting a return value. Ensure the method exists on the host object. ```javascript await chrome.webview.hostObjects.sample.MethodWithParametersAndReturnValue(paramValue1, paramValue2) ``` -------------------------------- ### Call Method with No Parameter Source: https://github.com/microsoftedge/webview2samples/blob/main/SampleApps/WebView2WpfBrowser/assets/hostObject.html Executes a host object method that does not require any parameters. The result is displayed in an alert box. ```javascript document.getElementById('methodNoParam').addEventListener('click', async () => { const bridge = chrome.webview.hostObjects.bridge; const result = await bridge.Func2(); alert(result); }); ``` -------------------------------- ### Open Pop-up Window with Virtual Host Mapping Source: https://github.com/microsoftedge/webview2samples/blob/main/SampleApps/WebView2APISample/assets/ScenarioVirtualHostMappingForPopUpWindow.html Use this JavaScript function to open a new pop-up window with a specified URL. Ensure that the URL is correctly mapped as a virtual host in your WebView2 environment. ```javascript function jump() { let url = "https://appassets.example/ScenarioVirtualHostMappingForPopUpWindow.html"; window.open(url); } ``` -------------------------------- ### Invoke Method Synchronously with Parameters and Return Value Source: https://github.com/microsoftedge/webview2samples/blob/main/SampleApps/WebView2APISample/assets/ScenarioAddHostObject.html Execute a method on a host object synchronously, providing parameters and obtaining a return value. Use this for quick, non-blocking operations. ```javascript const paramValue1 = document.getElementById("invokeMethodSyncParam1").value; const paramValue2 = parseInt(document.getElementById("invokeMethodSyncParam2").value); const resultValue = chrome.webview.hostObjects.sync.sample.MethodWithParametersAndReturnValue(paramValue1, paramValue2); document.getElementById("invokeMethodSyncOutput").textContent = resultValue; ``` -------------------------------- ### Call Async Void Method Source: https://github.com/microsoftedge/webview2samples/blob/main/SampleApps/WebView2WindowsFormsBrowser/assets/hostObject.html Illustrates calling an asynchronous method on the host object that returns void. The result is displayed in an alert. ```javascript document.getElementById('methodNoParamAsyncVoid').addEventListener('click', async () => { const bridge = chrome.webview.hostObjects.bridge; const result = await bridge.Func2AsyncTaskVoid(); alert(result); }); ``` -------------------------------- ### Handle WebView Message for Root Directory Source: https://github.com/microsoftedge/webview2samples/blob/main/SampleApps/WebView2APISample/assets/ScenarioFileSystemHandleShare.html Listens for messages from the WebView and renders the file explorer when a 'RootDirectoryHandle' message is received. ```javascript chrome.webview.addEventListener("message", function (e) { if (e.data.messageType === "RootDirectoryHandle") { renderFileExplorer(e.additionalObjects[0]); } }) ``` -------------------------------- ### Initialize WebView2 Shared Buffer Event Listener Source: https://github.com/microsoftedge/webview2samples/blob/main/SampleApps/WebView2WpfBrowser/assets/sharedBuffer.html Sets up the event listener for 'sharedbufferreceived' when the window loads. It also determines whether the current context is the top-level window or an iframe. ```javascript window.onload = function () { window.chrome.webview.addEventListener("sharedbufferreceived", e => { SharedBufferReceived(e); }); var classValue; var description; if (window.top === window) { var divSummary = document.getElementById("div-summary"); divSummary.style.display = 'block'; createIFrame(); classValue = "ICoreWebView2"; description = "page"; } else { classValue = "ICoreWebView2Frame"; description = "iframe"; } document.getElementById("class1").innerHTML = classValue; document.getElementById("page").innerHTML = description; }; ``` -------------------------------- ### Initialize Page and Update Stats Source: https://github.com/microsoftedge/webview2samples/blob/main/SampleApps/WebView2APISample/assets/ScenarioWebrtcUdpPortConfiguration.html Initializes the page by clearing content, hiding status/error elements, and updating statistics. This function is called on DOMContentLoaded. ```javascript ById('candidatesBody').innerHTML = ''; document.getElementById('status').style.display = 'none'; document.getElementById('error').style.display = 'none'; updateStats(); } // Initialize the page document.addEventListener('DOMContentLoaded', () => { updateStats(); }); ``` -------------------------------- ### Implement Save File Picker Source: https://github.com/microsoftedge/webview2samples/blob/main/SampleApps/WebView2APISample/assets/SecnarioFileTypePolicy.html This JavaScript code enables a save file picker, allowing users to choose a file name and location. It uses the `window.showSaveFilePicker` API and writes sample content to the selected file. ```javascript document.addEventListener('DOMContentLoaded', () => { async function saveFile() { let ext = document.getElementById("extensionText"); // Show the save file picker const newHandle = await window.showSaveFilePicker({ suggestedName: `sample_file.${ext.value}` }); // Write the content to the selected file const writable = await newHandle.createWritable(); await writable.write("sample sentence"); await writable.close(); } document.getElementById('showSaveFilePickerButton').addEventListener('click', saveFile); }); ``` -------------------------------- ### Open New Window with JavaScript Source: https://github.com/microsoftedge/webview2samples/blob/main/SampleApps/webview2_sample_uwp/Html/new_window.html Use this JavaScript function to open a new browser window with a URL specified in a data attribute. Ensure the target URL is valid. ```javascript function OpenWindow(button) { var url = button.getAttribute("data-url"); window.open(url, "_blank"); } ``` -------------------------------- ### Call Async Host Object Method with Parameter Source: https://github.com/microsoftedge/webview2samples/blob/main/SampleApps/WebView2WindowsFormsBrowser/assets/hostObject.html Invokes an asynchronous host object method that accepts a numeric parameter representing a delay. Prompts the user for the delay duration. ```javascript document.getElementById('methodAsync').addEventListener('click', async () => { const bridge = chrome.webview.hostObjects.bridge; const result = await bridge.FuncAsync(prompt('How many milliseconds should the async operation take? Enter zero or less to make it return immediately and synchronously.', '2000')); alert(result); }); ``` -------------------------------- ### Enable All Browser Accelerators Except Ctrl+P Source: https://github.com/microsoftedge/webview2samples/blob/main/SampleApps/WebView2APISample/assets/ScenarioAcceleratorKeyPressed.html This scenario implies enabling all browser accelerator keys while specifically disabling Ctrl+P. The provided code snippets are for enabling and disabling all accelerators, and specific logic would be needed to exclude Ctrl+P. ```javascript function EnableBrowserAccelerators() { window.chrome.webview.postMessage("EnableBrowserAccelerators"); } ``` ```javascript function DisableBrowserAccelerators() { window.chrome.webview.postMessage("DisableBrowserAccelerators"); } ``` -------------------------------- ### Run All Host Object Tests Source: https://github.com/microsoftedge/webview2samples/blob/main/SampleApps/WebView2WindowsFormsBrowser/assets/hostObject.html Executes a comprehensive suite of tests for host object interactions, including property access, method calls, and asynchronous operations. Ensure the 'bridge' object is correctly exposed. ```javascript document.getElementById('runTest').addEventListener('click', async () => { const bridge = chrome.webview.hostObjects.bridge; let expected_result = 'value1'; bridge.Prop = expected_result; let result = await bridge.Prop; assertEqual(result, expected_result, 'property on bridge'); const value2 = 'value2'; result = await bridge.Func(value2); expected_result = 'BridgeAddRemoteObject.Func(' + value2 + ')'; assertEqual(result, expected_result, 'method with parameter'); result = await bridge.Func2(); expected_result = 'BridgeAddRemoteObject.Func2()'; assertEqual(result, expected_result, 'method with no parameter'); result = await bridge.FuncAsync(500); expected_result = 'BridgeAddRemoteObject.FuncAsync(500)'; assertEqual(result, expected_result, 'async method with parameter'); result = await bridge.FuncAsyncTaskVoid(500); expected_result = null; assertEqual(result, expected_result, 'async method with parameter without result'); result = await bridge.Func2Async(); expected_result = 'BridgeAddRemoteObject.Func2Async()'; assertEqual(result, expected_result, 'async method with no parameter'); result = await bridge.Func2AsyncTaskVoid(); expected_result = null; assertEqual(result, expected_result, 'async method with no parameter without result'); result = await bridge.FuncAsync(0); expected_result = 'BridgeAddRemoteObject.FuncAsync(0)'; assertEqual(result, expected_result, 'async method with no delay'); const another_object = bridge.AnotherObject; another_object.Prop = value2; result = await another_object.Prop; expected_result = value2; assertEqual(result, expected_result, 'property on another_object'); chrome.webview.hostObjects.options.shouldSerializeDates = true; const date = new Date(); bridge.DateProp = date; const date2 = await bridge.DateProp; assertEqual(date2.getTime(), date.getTime(), 'test date object serialization'); let index = 123; expected_result = 'aa'; bridge[index] = expected_result; result = await bridge[index]; assertEqual(result, expected_result, 'bridge[index]'); index = 321; expected_result = 'bb'; bridge.Items[index] = expected_result; result = await bridge.Items[index]; assertEqual(result, expected_result, 'bridge.Items[index]'); let resolved_bridge = await bridge; result = await bridge.GetObjectType(resolved_bridge); expected_result = 'BridgeAddRemoteObject'; assertEqual(result, expected_result, 'type of resolved_bridge'); result = await bridge.GetObjectType(bridge); expected_result = 'BridgeAddRemoteObject'; assertEqual(result, expected_result, 'type of bridge'); result = await bridge.GetObjectType(another_object); expected_result = 'AnotherRemoteObject'; assertEqual(result, expected_result, 'type of another_object'); result = await bridge.GetObjectTypeAsync(another_object); expected_result = 'AnotherRemoteObject'; assertEqual(result, expected_result, 'type of another_object asynchronously'); alert('Test End'); }); ``` -------------------------------- ### Create and Load IFrame Source: https://github.com/microsoftedge/webview2samples/blob/main/SampleApps/WebView2WindowsFormsBrowser/assets/hostObject.html Creates an iframe element and appends it to the parent HTML page. This is useful for loading external content or separate components within the WebView. ```javascript function createIFrame() { var i = document.createElement("iframe"); i.src = "https://appassets.example/hostObject.html"; i.scrolling = "auto"; i.frameborder = "0"; i.height = "50%"; i.width = "100%"; i.name = "iframe_name"; var div = document.getElementById("div_iframe"); div.appendChild(i); div.style.display = 'block'; }; window.onload = function () { if (window.top === window) { createIFrame(); } }; ``` -------------------------------- ### Set Host Object Indexer with Alias Source: https://github.com/microsoftedge/webview2samples/blob/main/SampleApps/WebView2WpfBrowser/assets/hostObject.html Sets a value on a host object's indexer using an alias. Prompts the user for input. ```javascript document.getElementById('indexerSetAlias').addEventListener('click', async () => { const bridge = chrome.webview.hostObjects.bridge; bridge.Items[12] = prompt('Property text', 'Property text'); }); ``` -------------------------------- ### Set Property Async Source: https://github.com/microsoftedge/webview2samples/blob/main/SampleApps/WebView2APISample/assets/ScenarioAddHostObject.html Use this to asynchronously set a property on the host object. This method returns immediately without waiting for the property to be set. ```javascript chrome.webview.hostObjects.sample.property = propertyValue; ``` -------------------------------- ### Set Host Object Indexer Source: https://github.com/microsoftedge/webview2samples/blob/main/SampleApps/WebView2WpfBrowser/assets/hostObject.html Sets a value on a host object's indexer. Prompts the user for input. ```javascript document.getElementById('indexerSet').addEventListener('click', async () => { const bridge = chrome.webview.hostObjects.bridge; bridge[1] = prompt('Property text', 'Property text'); }); ``` -------------------------------- ### Post Message to Set Permission - JavaScript Source: https://github.com/microsoftedge/webview2samples/blob/main/SampleApps/WebView2APISample/assets/ScenarioPermissionManagement.html Sends a 'SetPermission' message to the WebView2 host. This action typically triggers a permission update. ```javascript function setPermission() { chrome.webview.postMessage("SetPermission"); } ``` -------------------------------- ### Handle WebView2 Messages Source: https://github.com/microsoftedge/webview2samples/blob/main/SampleApps/WebView2APISample/assets/ScenarioNotificationReceived.html Listens for messages from the WebView2 environment and adds them to the notification log. Ensure the WebView2 environment is configured to send messages. ```javascript function clearList() { let log = document.getElementById('notificationLog'); log.innerHTML = ''; } function createListItem(name) { let dt = document.createElement('dt'); dt.textContent = name; return dt; } function addItem(name) { const log = document.querySelector('#notificationLog'); log.appendChild(createListItem(name)); } chrome.webview.addEventListener("message", args => { addItem(args.data); }); window.addEventListener("unload", (event) => { clearList(); }); ``` -------------------------------- ### Navigate WebView to a URL Source: https://github.com/microsoftedge/webview2samples/blob/main/SampleApps/WebView2SampleWinComp/WebView2SamplePage.html Attaches an event listener to a button to navigate the WebView to a specified URL when clicked. Ensure the button with id 'myButton' exists in the HTML. ```javascript document.getElementById("myButton").onclick = function () { location.href = "https://www.bing.com/"; }; ``` -------------------------------- ### Create and Post Message to Dedicated Worker Source: https://github.com/microsoftedge/webview2samples/blob/main/SampleApps/WebView2APISample/assets/ScenarioDedicatedWorkerPostMessage.html Creates a dedicated worker and posts a message to it. The worker expects a JSON string with a command and two numbers. ```javascript const worker = new Worker("dedicated_worker.js"); ``` -------------------------------- ### Call Async Method with No Parameter Source: https://github.com/microsoftedge/webview2samples/blob/main/SampleApps/WebView2WpfBrowser/assets/hostObject.html Calls an asynchronous host object method that takes no arguments. The outcome of the operation is shown in an alert. ```javascript document.getElementById('methodNoParamAsync').addEventListener('click', async () => { const bridge = chrome.webview.hostObjects.bridge; const result = await bridge.Func2Async(); alert(result); }); ``` -------------------------------- ### Invoke Method Asynchronously with Parameters and Return Value Source: https://github.com/microsoftedge/webview2samples/blob/main/SampleApps/WebView2APISample/assets/ScenarioAddHostObject.html Call a method on a host object asynchronously, passing parameters and receiving a return value. This is suitable for operations that may take time. ```javascript const paramValue1 = document.getElementById("invokeMethodAsyncParam1").value; const paramValue2 = parseInt(document.getElementById("invokeMethodAsyncParam2").value); const resultValue = await chrome.webview.hostObjects.sample.MethodWithParametersAndReturnValue(paramValue1, paramValue2); document.getElementById("invokeMethodAsyncOutput").textContent = resultValue; ``` -------------------------------- ### Set Property Synchronously Source: https://github.com/microsoftedge/webview2samples/blob/main/SampleApps/WebView2APISample/assets/ScenarioAddHostObject.html Use this to set a property on a host object synchronously. Ensure the host object property is accessible. ```javascript document.getElementById("setPropertySyncInput").value; chrome.webview.hostObjects.sync.sample.property = propertyValue; document.getElementById("setPropertySyncOutput").textContent = "Set"; ``` -------------------------------- ### Notification Options Configuration Source: https://github.com/microsoftedge/webview2samples/blob/main/SampleApps/WebView2APISample/assets/ScenarioNotificationReceived.html Defines the configuration options for displaying a non-persistent notification, including body, icon, image, badge, tag, and interaction behavior. ```javascript var nonPersistentNotificationCount = 0; var nonPersistentTitle = 'Test Non-Persistent Notification Title'; var options = { body: 'Test Notification Body', icon: 'images/icon.png', image: 'images/image.png', badge: 'images/badge.png', tag: 'notification-tag', renotify: false, requireInteraction: false, silent: false, vibrate: [100, 50, 100], timestamp: Date.now(), }; ``` -------------------------------- ### Invoke Method Sync Source: https://github.com/microsoftedge/webview2samples/blob/main/SampleApps/WebView2APISample/assets/ScenarioAddHostObject.html Synchronously call a method on the host object, passing parameters. This operation will block until the method execution completes. ```javascript chrome.webview.hostObjects.sync.sample.MethodWithParametersAndReturnValue(paramValue1, paramValue2) ``` -------------------------------- ### Control Executable File Policy Source: https://github.com/microsoftedge/webview2samples/blob/main/SampleApps/WebView2APISample/assets/SecnarioFileTypePolicy.html These JavaScript functions send messages to the WebView2 environment to manage policies for executable files. Use these to allow, block, or clear policies related to .exe downloads. ```javascript function enable_smartscreen() { window.chrome.webview.postMessage("enable_smartscreen"); } ``` ```javascript function disable_smartscreen() { window.chrome.webview.postMessage("disable_smartscreen"); } ``` ```javascript function allow_exe() { window.chrome.webview.postMessage("allow_exe"); } ``` ```javascript function block_exe() { window.chrome.webview.postMessage("block_exe"); } ``` ```javascript function clear_exe_policy() { window.chrome.webview.postMessage("clear_exe_policy"); } ``` -------------------------------- ### Check Periodic Background Sync Permission Source: https://github.com/microsoftedge/webview2samples/blob/main/SampleApps/WebView2APISample/assets/ScenarioServiceWorkerSyncRegistrationManager.html Checks if the 'periodic-background-sync' permission is granted. Ensure this permission is handled before attempting to register sync tasks. ```javascript async function checkPermission() { const status = await navigator.permissions.query({name: 'periodic-background-sync'}); if (status.state === 'granted') { console.log("periodic-background-sync permission is granted"); } else { console.log("periodic-background-sync permission is denied"); } } ``` -------------------------------- ### Request Window Bounds from Host Source: https://github.com/microsoftedge/webview2samples/blob/main/SampleApps/WebView2APISample/assets/ScenarioWebMessage.html Sends a 'GetWindowBounds' message to the host app to retrieve window dimensions. Requires the 'chrome.webview' API. ```javascript function GetWindowBounds() { window.chrome.webview.postMessage("GetWindowBounds"); } ``` -------------------------------- ### Handle WebView Messages Source: https://github.com/microsoftedge/webview2samples/blob/main/SampleApps/WebView2APISample/assets/ScenarioWebViewEventMonitor.html Listens for messages from the WebView, displays the event name, and populates a details view with event arguments and WebView properties when an event name is clicked. ```javascript chrome.webview.addEventListener("message", args => { const nameElement = document.createElement("div"); nameElement.textContent = args.data.name; nameElement.addEventListener("click", () => { details.textContent = ""; details.appendChild(textToHtml(args.data.name + " event args", true)); details.appendChild(objectToHtml("", args.data.args)); details.appendChild(textToHtml("WebView properties", true)); details.appendChild(objectToHtml("", args.data.webview)); }); eventList.appendChild(nameElement); }); ``` -------------------------------- ### Enable Web Worker Host Object Interaction Source: https://github.com/microsoftedge/webview2samples/blob/main/SampleApps/WebView2APISample/assets/ScenarioAddHostObject.html This JavaScript code enables interaction with host objects from a Web Worker. It sets up a worker, listens for messages, and enables a scenario when the host object is detected. ```javascript function enableWebWorker() { // The worker can also use the host object if the SDK supports. window.worker = new Worker("https://appassets.example/ScenarioAddHostObjectWorker-Staging.js"); window.setDateViaWorkerEnabled = false; worker.onmessage = function (e) { // If the worker can detect the host object, it will let the main page know // so we can enable the web worker scenario. if (e.data === "HostObjectDetected") { enableWebWorkerScenario(); } else if (window.setDateViaWorkerEnabled) { // The worker will frequently pass the date it obtained from the host object. document.getElementById("dateOutput").textContent = "sample.dateProperty via worker: " + e.data; } }; } function enableWebWorkerScenario() { document.getElementById("worker").style.visibility = "visible"; } function toggleSetTimeViaWorker() { window.setDateViaWorkerEnabled = !window.setDateViaWorkerEnabled; if (window.setDateViaWorkerEnabled) { window.worker.postMessage("enable"); } else { window.worker.postMessage("disable"); } } ``` -------------------------------- ### Create and Append IFrame Source: https://github.com/microsoftedge/webview2samples/blob/main/SampleApps/WebView2WindowsFormsBrowser/assets/webMessages.html Dynamically creates an iframe element, sets its properties, and appends it to a div on the page. Used for embedding external content. ```javascript function createIFrame() { var i = document.createElement("iframe"); i.src = "https://appassets.example/webMessages.html"; i.scrolling = "auto"; i.frameborder = "0"; i.height = "90%"; i.width = "100%"; i.name = "iframe\_name"; var div = document.getElementById("div_iframe"); div.appendChild(i); div.style.display = 'block'; }; ``` -------------------------------- ### Create Menu Item - JavaScript Source: https://github.com/microsoftedge/webview2samples/blob/main/SampleApps/WebView2APISample/assets/ScenarioPermissionManagement.html Creates a new list item element for displaying permission names. This is a helper function for adding items to the list. ```javascript function createMenuItem(name) { let li = document.createElement('li'); li.textContent = name; return li; } ``` -------------------------------- ### Set Indexed Property Async Source: https://github.com/microsoftedge/webview2samples/blob/main/SampleApps/WebView2APISample/assets/ScenarioAddHostObject.html Set a property on the host object using an index asynchronously. Both the index and the new value are provided. ```javascript chrome.webview.hostObjects.sync.indexedProperty[paramValue1] = paramValue2 ``` -------------------------------- ### Set Property Sync Source: https://github.com/microsoftedge/webview2samples/blob/main/SampleApps/WebView2APISample/assets/ScenarioAddHostObject.html Use this to synchronously set a property on the host object. This operation will block until the property is set. ```javascript chrome.webview.hostObjects.sync.sample.property = value; ``` -------------------------------- ### Create and Append IFrame Source: https://github.com/microsoftedge/webview2samples/blob/main/SampleApps/WebView2APISample/assets/ScenarioWebMessage.html Dynamically creates an iframe element and appends it to a div container. Used for embedding external content within the webview. ```javascript //! [chromeWebView] function createIFrame() { var i = document.createElement("iframe"); i.src = "https://appassets.example/ScenarioWebMessage.html"; i.scrolling = "auto"; i.frameborder = "0"; i.height = "90%"; i.width = "100%"; i.name = "iframe_name"; var div = document.getElementById("div_iframe"); div.appendChild(i); div.style.display = 'block'; }; ```