WebView class
window.chrome.webview
是用于访问特定于 WebView2 的 API 的类,这些 API 可用于在 WebView2 运行时中运行的脚本。
- 扩展
属性
host |
包含通过 如果在本机代码中调用 |
方法
add |
标准 |
post |
当页面调用 |
post |
当页面调用 |
release |
使用 |
remove |
标准 |
属性详细信息
hostObjects
包含通过 CoreWebView2.AddHostObjectToScript
添加的所有主机对象的异步代理,以及用于配置这些代理的选项,以及用于同步代理的容器。
如果在本机代码中调用 coreWebView2.AddHostObjectToScript("myObject", object);
,则 通过使用 chrome.webview.hostObjects.myObject
,Web 端代码可以使用 异步代理object
。
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();
};
使用 AddHostObjectToScript
将此接口的实例添加到 JavaScript 中。 在这种情况下,请将它 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
事件通过 CoreWebView2.PostWebMessageAsJson
或 CoreWebView2.PostWebMessageAsString
接收从 WebView2 主机发布的消息。 该 sharedbufferreceived
事件通过 CoreWebView2.PostSharedBufferToScript
接收从 WebView2 主机发布的共享缓冲区。
请参阅 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
将按照与“postMessage”相同的方式发送到 WebView2。 作为“additionalObjects”传递的对象将转换为其本机类型,并在 属性中 CoreWebView2WebMessageReceivedEventArgs.AdditionalObjects
可用。
postMessageWithAdditionalObjects(message: any, additionalObjects: ArrayLike<any>) : void;
参数
- message
-
any
要发送到 WebView2 主机的消息。 这可以是可序列化为 JSON 的任何对象。
- additionalObjects
-
ArrayLike<any>
在 WebView2 中具有本机表示形式的 DOM 对象的序列。 此参数必须是 ArrayLike。 以下 DOM 类型映射到本机:
DOM | Win32 | .NET | WinRT |
---|---|---|---|
文件 | ICoreWebView2File | System.IO.FileInfo | Windows.Storage.StorageFile |
null
或 undefined
条目将在 WebView2 中作为 null
类型传递。 否则,如果通过此 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