WebView class

window.chrome.webview — это класс для доступа к API-интерфейсам WebView2, которые доступны для скрипта, выполняющегося в среде выполнения WebView2.

Extends

Свойства

hostObjects

Содержит асинхронные прокси-серверы для всех объектов узла, добавленных с помощью CoreWebView2.AddHostObjectToScript , а также параметры для настройки этих прокси-серверов и контейнер для синхронных прокси-серверов.

При вызове coreWebView2.AddHostObjectToScript("myObject", object); в машинном коде асинхронный прокси-сервер для object доступен для веб-кода с помощью chrome.webview.hostObjects.myObject.

Методы

addEventListener(type, listener, options)

Стандартный EventTarget.addEventListener метод. Используйте его для подписки на message событие или sharedbufferreceived событие. Событие message получает сообщения, опубликованные с узла WebView2 через CoreWebView2.PostWebMessageAsJson или CoreWebView2.PostWebMessageAsString. Событие sharedbufferreceived получает общие буферы, размещенные с узла WebView2 через CoreWebView2.PostSharedBufferToScript. См. раздел CoreWebView2.PostWebMessageAsJson( Win32/C++, .NET, WinRT).

postMessage(message)

Когда страница вызывает postMessage, message параметр преобразуется в JSON и асинхронно размещается в хост-процессе WebView2. Это приведет к возникновению CoreWebView2.WebMessageReceived события или CoreWebView2Frame.WebMessageReceived события в зависимости от того, вызывается ли postMessage он из документа верхнего уровня в WebView2 или из дочернего кадра. См. раздел CoreWebView2.WebMessageReceived( Win32/C++, .NET, WinRT). См. раздел CoreWebView2Frame.WebMessageReceived( Win32/C++, .NET, WinRT).

postMessageWithAdditionalObjects(message, additionalObjects)

Когда страница вызывает postMessageWithAdditionalObjects, message параметр отправляется в WebView2 таким же образом, как postMessage. Объекты, переданные как "additionalObjects", преобразуются в собственные типы и будут доступны в свойстве CoreWebView2WebMessageReceivedEventArgs.AdditionalObjects .

releaseBuffer(buffer)

Вызовите с ArrayBuffer помощью из chrome.webview.sharedbufferreceived события, чтобы освободить базовый ресурс общей памяти.

removeEventListener(type, listener, options)

Стандартный EventTarget.removeEventListener метод. Используйте его для отмены подписки на message событие или sharedbufferreceived .

Сведения о свойстве

hostObjects

Содержит асинхронные прокси-серверы для всех объектов узла, добавленных с помощью CoreWebView2.AddHostObjectToScript , а также параметры для настройки этих прокси-серверов и контейнер для синхронных прокси-серверов.

При вызове coreWebView2.AddHostObjectToScript("myObject", object); в машинном коде асинхронный прокси-сервер для object доступен для веб-кода с помощью chrome.webview.hostObjects.myObject.

hostObjects: HostObjectsAsyncRoot;

Значение свойства

Примеры

Например, предположим, что у вас есть com-объект со следующим интерфейсом:

[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();
};

Добавьте экземпляр этого интерфейса в JavaScript с помощью AddHostObjectToScript. В этом случае присвойте ему sampleимя .

В коде собственного ведущего приложения:

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();

В HTML-документе используйте com-объект с помощью 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;
});

Сведения о методе

addEventListener(type, listener, options)

Стандартный EventTarget.addEventListener метод. Используйте его для подписки на message событие или sharedbufferreceived событие. Событие message получает сообщения, опубликованные с узла WebView2 через CoreWebView2.PostWebMessageAsJson или CoreWebView2.PostWebMessageAsString. Событие sharedbufferreceived получает общие буферы, размещенные с узла WebView2 через CoreWebView2.PostSharedBufferToScript. См. раздел CoreWebView2.PostWebMessageAsJson( Win32/C++, .NET, WinRT).

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

Параметры

type

string

Имя события, на которое нужно подписаться. Допустимые значения: message, и sharedbufferreceived.

listener

EventListenerOrEventListenerObject

Обратный вызов, вызываемый при возникновении события.

options

boolean | AddEventListenerOptions

Параметры для управления обработкой события.

Возвращаемое значение

void

postMessage(message)

Когда страница вызывает postMessage, message параметр преобразуется в JSON и асинхронно размещается в хост-процессе WebView2. Это приведет к возникновению CoreWebView2.WebMessageReceived события или CoreWebView2Frame.WebMessageReceived события в зависимости от того, вызывается ли postMessage он из документа верхнего уровня в WebView2 или из дочернего кадра. См. раздел CoreWebView2.WebMessageReceived( Win32/C++, .NET, WinRT). См. раздел CoreWebView2Frame.WebMessageReceived( Win32/C++, .NET, WinRT).

postMessage(message: any) : void;

Параметры

message

any

Сообщение для отправки на узел WebView2. Это может быть любой объект, который можно сериализовать в ФОРМАТЕ JSON.

Возвращаемое значение

void

Комментарии

Примеры

Опубликуй сообщение в :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)

Когда страница вызывает postMessageWithAdditionalObjects, message параметр отправляется в WebView2 таким же образом, как postMessage. Объекты, переданные как "additionalObjects", преобразуются в собственные типы и будут доступны в свойстве CoreWebView2WebMessageReceivedEventArgs.AdditionalObjects .

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

Параметры

message

any

Сообщение для отправки на узел WebView2. Это может быть любой объект, который можно сериализовать в ФОРМАТЕ JSON.

additionalObjects

ArrayLike<any>

Последовательность объектов DOM с собственными представлениями в WebView2. Этот параметр должен иметь значение ArrayLike. Следующие типы DOM сопоставляются с собственным:

DOM Win32 .NET Winrt
Файл ICoreWebView2File System.IO.FileInfo Windows.Storage.StorageFile

null или undefined записи передаются как null тип в WebView2. В противном случае, если через этот API передается недопустимый или неподдерживаемый объект, возникнет исключение, и сообщение не будет отправлено.

Возвращаемое значение

void

Комментарии

Примеры

Опубликуйте сообщение, содержащее объекты File из входного элемента, в 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)

Вызовите с ArrayBuffer помощью из chrome.webview.sharedbufferreceived события, чтобы освободить базовый ресурс общей памяти.

releaseBuffer(buffer: ArrayBuffer): void;

Параметры

buffer

ArrayBuffer

Объект ArrayBuffer из chrome.webview.sharedbufferreceived события.

Возвращаемое значение

void

removeEventListener(type, listener, options)

Стандартный EventTarget.removeEventListener метод. Используйте его для отмены подписки на message событие или sharedbufferreceived .

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

Параметры

type

string

Имя события, на которое требуется отменить подписку. Допустимые значения: message и sharedbufferreceived.

listener

EventListenerOrEventListenerObject

Обратный вызов, удаляемый из события.

options

boolean | EventListenerOptions

Параметры для управления обработкой события.

Возвращаемое значение

void