WebView class
window.chrome.webview é a classe para acessar as APIs específicas do WebView2 que estão disponíveis para o script em execução no WebView2 Runtime.
- Extends
Propriedades
| host |
Contém proxies assíncronos para todos os objetos host adicionados por meio deles Se você chamar |
Métodos
| add |
O método padrão |
| post |
Quando a página chama |
| post |
Quando a página chama |
| release |
Chame com o |
| remove |
O método padrão |
Detalhes da propriedade
hostObjects
Contém proxies assíncronos para todos os objetos host adicionados por meio deles CoreWebView2.AddHostObjectToScript , bem como opções para configurar esses proxies e o contêiner para proxies síncronos.
Se você chamar coreWebView2.AddHostObjectToScript("myObject", object); seu código nativo, um proxy assíncrono para object estará disponível para seu código do lado da Web, usando chrome.webview.hostObjects.myObject.
hostObjects: HostObjectsAsyncRoot;
Valor da propriedade
Exemplos
Por exemplo, suponha que você tenha um objeto COM com a seguinte 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();
};
Adicione uma instância desta interface em seu JavaScript com AddHostObjectToScript. Nesse caso, nomeie-o samplecomo .
No código do aplicativo host nativo:
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();
No documento HTML, use o objeto COM usando 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;
});
Detalhes do método
addEventListener(type, listener, options)
O método padrão EventTarget.addEventListener . Use-o para se inscrever no message evento ou sharedbufferreceived evento. O message evento recebe mensagens postadas do host WebView2 por meio CoreWebView2.PostWebMessageAsJson de ou CoreWebView2.PostWebMessageAsString. O sharedbufferreceived evento recebe buffers compartilhados postados do host WebView2 por meio CoreWebView2.PostSharedBufferToScriptdo .
Consulte CoreWebView2.PostWebMessageAsJson( Win32/C++, .NET, WinRT).
addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;
Parâmetros
- type
-
string
O nome do evento no qual se inscrever. Os valores válidos são message, e sharedbufferreceived.
- listener
-
EventListenerOrEventListenerObject
O retorno de chamada a ser invocado quando o evento é gerado.
- options
-
boolean | AddEventListenerOptions
Opções para controlar como o evento é tratado.
Retornos
void
postMessage(message)
Quando a página chama postMessage, o message parâmetro é convertido em JSON e é postado de forma assíncrona no processo de host WebView2. Isso resultará no evento ou CoreWebView2Frame.WebMessageReceived no CoreWebView2.WebMessageReceived evento sendo gerado, dependendo se postMessage for chamado do documento de nível superior no WebView2 ou de um quadro filho. Consulte CoreWebView2.WebMessageReceived( Win32/C++, .NET, WinRT). Consulte CoreWebView2Frame.WebMessageReceived( Win32/C++, .NET, WinRT).
postMessage(message: any) : void;
Parâmetros
- message
-
any
A mensagem a ser enviada ao host WebView2. Pode ser qualquer objeto que possa ser serializado em JSON.
Retornos
void
Comentários
Exemplos
Poste uma mensagem para o 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)
Quando a página chama postMessageWithAdditionalObjects, o message parâmetro é enviado para WebView2 da mesma forma que 'postMessage'. Os objetos passados como 'additionalObjects' são convertidos em seus tipos nativos e estarão disponíveis na CoreWebView2WebMessageReceivedEventArgs.AdditionalObjects propriedade.
postMessageWithAdditionalObjects(message: any, additionalObjects: ArrayLike<any>) : void;
Parâmetros
- message
-
any
A mensagem a ser enviada ao host WebView2. Pode ser qualquer objeto que possa ser serializado em JSON.
- additionalObjects
-
ArrayLike<any>
Uma sequência de objetos DOM que têm representações nativas no WebView2. Esse parâmetro precisa ser ArrayLike. Os seguintes tipos de DOM são mapeados para nativo:
| DOM | Win32 | .NET | WinRT |
|---|---|---|---|
| Arquivo | ICoreWebView2File | System.IO.FileInfo | Windows.Storage.StorageFile |
null ou undefined entradas serão passadas como null tipo no WebView2. Caso contrário, se um objeto inválido ou sem suporte for passado por essa API, uma exceção será lançada e a mensagem não será postada.
Retornos
void
Comentários
Exemplos
Poste uma mensagem que inclua objetos File de um elemento de entrada para o 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)
Chame com o ArrayBuffer do evento para liberar o recurso de chrome.webview.sharedbufferreceived memória compartilhada subjacente.
releaseBuffer(buffer: ArrayBuffer): void;
Parâmetros
- buffer
-
ArrayBuffer
Um ArrayBuffer do chrome.webview.sharedbufferreceived evento.
Retornos
void
removeEventListener(type, listener, options)
O método padrão EventTarget.removeEventListener . Use-o para cancelar a assinatura do message evento or sharedbufferreceived .
removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;
Parâmetros
- type
-
string
O nome do evento do qual cancelar a assinatura. Os valores válidos são message e sharedbufferreceived.
- listener
-
EventListenerOrEventListenerObject
O retorno de chamada a ser removido do evento.
- options
-
boolean | EventListenerOptions
Opções para controlar como o evento é tratado.
Retornos
void