Edit

Share via


WebView class

window.chrome.webview is the class to access the WebView2-specific APIs that are available to the script running within WebView2 Runtime.

Extends

Properties

hostObjects

Contains asynchronous proxies for all host objects added via CoreWebView2.AddHostObjectToScript as well as options to configure those proxies, and the container for synchronous proxies.

If you call coreWebView2.AddHostObjectToScript("myObject", object); in your native code, an asynchronous proxy for object is available to your web-side code, by using chrome.webview.hostObjects.myObject.

Methods

addEventListener(type, listener, options)

The standard EventTarget.addEventListener method. Use it to subscribe to the message event or sharedbufferreceived event. The message event receives messages posted from the WebView2 host via CoreWebView2.PostWebMessageAsJson or CoreWebView2.PostWebMessageAsString. The sharedbufferreceived event receives shared buffers posted from the WebView2 host via CoreWebView2.PostSharedBufferToScript. See CoreWebView2.PostWebMessageAsJson( Win32/C++, .NET, WinRT).

postMessage(message)

When the page calls postMessage, the message parameter is converted to JSON and is posted asynchronously to the WebView2 host process. This will result in either the CoreWebView2.WebMessageReceived event or the CoreWebView2Frame.WebMessageReceived event being raised, depending on if postMessage is called from the top-level document in the WebView2 or from a child frame. See CoreWebView2.WebMessageReceived( Win32/C++, .NET, WinRT). See CoreWebView2Frame.WebMessageReceived( Win32/C++, .NET, WinRT).

postMessageWithAdditionalObjects(message, additionalObjects)

When the page calls postMessageWithAdditionalObjects, the message parameter is sent to WebView2 in the same fashion as 'postMessage'. Objects passed as 'additionalObjects' are converted to their native types and will be available in the CoreWebView2WebMessageReceivedEventArgs.AdditionalObjects property.

releaseBuffer(buffer)

Call with the ArrayBuffer from the chrome.webview.sharedbufferreceived event to release the underlying shared memory resource.

removeEventListener(type, listener, options)

The standard EventTarget.removeEventListener method. Use it to unsubscribe to the message or sharedbufferreceived event.

Property Details

hostObjects

Contains asynchronous proxies for all host objects added via CoreWebView2.AddHostObjectToScript as well as options to configure those proxies, and the container for synchronous proxies.

If you call coreWebView2.AddHostObjectToScript("myObject", object); in your native code, an asynchronous proxy for object is available to your web-side code, by using chrome.webview.hostObjects.myObject.

hostObjects: HostObjectsAsyncRoot;

Property Value

Examples

For example, suppose you have a COM object with the following interface:

[uuid(3a14c9c0-bc3e-453f-a314-4ce4a0ec81d8), object, local]
interface IHostObjectSample : IUnknown
{
    // Demonstrate basic method call with some parameters and a return value.
    HRESULT MethodWithParametersAndReturnValue([in] BSTR stringParameter, [in] INT integerParameter, [out, retval] BSTR* stringResult);

    // Demonstrate getting and setting a property.
    [propget] HRESULT Property([out, retval] BSTR* stringResult);
    [propput] HRESULT Property([in] BSTR stringValue);

    [propget] HRESULT IndexedProperty(INT index, [out, retval] BSTR * stringResult);
    [propput] HRESULT IndexedProperty(INT index, [in] BSTR stringValue);

    // Demonstrate native calling back into JavaScript.
    HRESULT CallCallbackAsynchronously([in] IDispatch* callbackParameter);

    // Demonstrate a property which uses Date types
    [propget] HRESULT DateProperty([out, retval] DATE * dateResult);
    [propput] HRESULT DateProperty([in] DATE dateValue);

    // Creates a date object on the native side and sets the DateProperty to it.
    HRESULT CreateNativeDate();
};

Add an instance of this interface into your JavaScript with AddHostObjectToScript. In this case, name it sample.

In the native host app code:

VARIANT remoteObjectAsVariant = {};
m_hostObject.query_to<IDispatch>(&remoteObjectAsVariant.pdispVal);
remoteObjectAsVariant.vt = VT_DISPATCH;

// We can call AddHostObjectToScript multiple times in a row without // calling RemoveHostObject first. This will replace the previous object // with the new object. In our case, this is the same object, and everything // is fine.
CHECK_FAILURE(
    m_webView->AddHostObjectToScript(L"sample", &remoteObjectAsVariant));
remoteObjectAsVariant.pdispVal->Release();

In the HTML document, use the COM object using chrome.webview.hostObjects.sample.

document.getElementById("getPropertyAsyncButton").addEventListener("click", async () => {
    const propertyValue = await chrome.webview.hostObjects.sample.property;
    document.getElementById("getPropertyAsyncOutput").textContent = propertyValue;
});

document.getElementById("getPropertySyncButton").addEventListener("click", () => {
    const propertyValue = chrome.webview.hostObjects.sync.sample.property;
    document.getElementById("getPropertySyncOutput").textContent = propertyValue;
});

document.getElementById("setPropertyAsyncButton").addEventListener("click", async () => {
    const propertyValue = document.getElementById("setPropertyAsyncInput").value;
    // The following line will work but it will return immediately before the property value has actually been set.
    // If you need to set the property and wait for the property to change value, use the setHostProperty function.
    chrome.webview.hostObjects.sample.property = propertyValue;
    document.getElementById("setPropertyAsyncOutput").textContent = "Set";
});

document.getElementById("setPropertyExplicitAsyncButton").addEventListener("click", async () => {
    const propertyValue = document.getElementById("setPropertyExplicitAsyncInput").value;
    // If you care about waiting until the property has actually changed value, use the setHostProperty function.
    await chrome.webview.hostObjects.sample.setHostProperty("property", propertyValue);
    document.getElementById("setPropertyExplicitAsyncOutput").textContent = "Set";
});

document.getElementById("setPropertySyncButton").addEventListener("click", () => {
    const propertyValue = document.getElementById("setPropertySyncInput").value;
    chrome.webview.hostObjects.sync.sample.property = propertyValue;
    document.getElementById("setPropertySyncOutput").textContent = "Set";
});

document.getElementById("getIndexedPropertyAsyncButton").addEventListener("click", async () => {
    const index = parseInt(document.getElementById("getIndexedPropertyAsyncParam").value);
    const resultValue = await chrome.webview.hostObjects.sample.IndexedProperty[index];
    document.getElementById("getIndexedPropertyAsyncOutput").textContent = resultValue;
});
document.getElementById("setIndexedPropertyAsyncButton").addEventListener("click", async () => {
    const index = parseInt(document.getElementById("setIndexedPropertyAsyncParam1").value);
    const value = document.getElementById("setIndexedPropertyAsyncParam2").value;;
    chrome.webview.hostObjects.sample.IndexedProperty[index] = value;
    document.getElementById("setIndexedPropertyAsyncOutput").textContent = "Set";
});
document.getElementById("invokeMethodAsyncButton").addEventListener("click", async () => {
    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;
});

document.getElementById("invokeMethodSyncButton").addEventListener("click", () => {
    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;
});

let callbackCount = 0;
document.getElementById("invokeCallbackButton").addEventListener("click", async () => {
    chrome.webview.hostObjects.sample.CallCallbackAsynchronously(() => {
        document.getElementById("invokeCallbackOutput").textContent = "Native object called the callback " + (++callbackCount) + " time(s).";
    });
});

// Date property
document.getElementById("setDateButton").addEventListener("click", () => {
    chrome.webview.hostObjects.options.shouldSerializeDates = true;
    chrome.webview.hostObjects.sync.sample.dateProperty = new Date();
    document.getElementById("dateOutput").textContent = "sample.dateProperty: " + chrome.webview.hostObjects.sync.sample.dateProperty;
});
document.getElementById("createRemoteDateButton").addEventListener("click", () => {
    chrome.webview.hostObjects.sync.sample.createNativeDate();
    document.getElementById("dateOutput").textContent = "sample.dateProperty: " + chrome.webview.hostObjects.sync.sample.dateProperty;
});

Method Details

addEventListener(type, listener, options)

The standard EventTarget.addEventListener method. Use it to subscribe to the message event or sharedbufferreceived event. The message event receives messages posted from the WebView2 host via CoreWebView2.PostWebMessageAsJson or CoreWebView2.PostWebMessageAsString. The sharedbufferreceived event receives shared buffers posted from the WebView2 host via CoreWebView2.PostSharedBufferToScript. See CoreWebView2.PostWebMessageAsJson( Win32/C++, .NET, WinRT).

addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;

Parameters

type

string

The name of the event to subscribe to. Valid values are message, and sharedbufferreceived.

listener

EventListenerOrEventListenerObject

The callback to invoke when the event is raised.

options

boolean | AddEventListenerOptions

Options to control how the event is handled.

Returns

void

postMessage(message)

When the page calls postMessage, the message parameter is converted to JSON and is posted asynchronously to the WebView2 host process. This will result in either the CoreWebView2.WebMessageReceived event or the CoreWebView2Frame.WebMessageReceived event being raised, depending on if postMessage is called from the top-level document in the WebView2 or from a child frame. See CoreWebView2.WebMessageReceived( Win32/C++, .NET, WinRT). See CoreWebView2Frame.WebMessageReceived( Win32/C++, .NET, WinRT).

postMessage(message: any) : void;

Parameters

message

any

The message to send to the WebView2 host. This can be any object that can be serialized to JSON.

Returns

void

Remarks

Examples

Post a message to the CoreWebView2:

const inTopLevelFrame = (window === window.parent);
if (inTopLevelFrame) {
    // The message can be any JSON serializable object.
    window.chrome.webview.postMessage({
        myMessage: 'Hello from the script!',
        otherValue: 1}
    );
    // A simple string is an example of a JSON serializable object.
    window.chrome.webview.postMessage("example");
}

postMessageWithAdditionalObjects(message, additionalObjects)

When the page calls postMessageWithAdditionalObjects, the message parameter is sent to WebView2 in the same fashion as 'postMessage'. Objects passed as 'additionalObjects' are converted to their native types and will be available in the CoreWebView2WebMessageReceivedEventArgs.AdditionalObjects property.

postMessageWithAdditionalObjects(message: any, additionalObjects: ArrayLike<any>) : void;

Parameters

message

any

The message to send to the WebView2 host. This can be any object that can be serialized to JSON.

additionalObjects

ArrayLike<any>

A sequence of DOM objects that have native representations in WebView2. This parameter needs to be ArrayLike. The following DOM types are mapped to native:

DOM Win32 .NET WinRT
File ICoreWebView2File System.IO.FileInfo Windows.Storage.StorageFile

null or undefined entries will be passed as null type in WebView2. Otherwise if an invalid or unsupported object is passed via this API, an exception will be thrown and the message will fail to post.

Returns

void

Remarks

Examples

Post a message that includes File objects from an input element to the CoreWebView2:

const input = document.getElementById('files');
input.addEventListener('change', function() {
    // 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.
    const currentFiles = input.files;
    chrome.webview.postMessageWithAdditionalObjects("FilesDropped",
        currentFiles);
});

releaseBuffer(buffer)

Call with the ArrayBuffer from the chrome.webview.sharedbufferreceived event to release the underlying shared memory resource.

releaseBuffer(buffer: ArrayBuffer): void;

Parameters

buffer

ArrayBuffer

An ArrayBuffer from the chrome.webview.sharedbufferreceived event.

Returns

void

removeEventListener(type, listener, options)

The standard EventTarget.removeEventListener method. Use it to unsubscribe to the message or sharedbufferreceived event.

removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;

Parameters

type

string

The name of the event to unsubscribe from. Valid values are message and sharedbufferreceived.

listener

EventListenerOrEventListenerObject

The callback to remove from the event.

options

boolean | EventListenerOptions

Options to control how the event is handled.

Returns

void