ICoreWebView2.add_WebMessageReceived

Add an event handler for the WebMessageReceived event. WebMessageReceived runs when the ICoreWebView2Settings::IsWebMessageEnabled setting is set and the top-level document of the WebView runs window.chrome.webview.postMessage. The postMessage function is void postMessage(object) where object is any object supported by JSON conversion.

\snippet assets\ScenarioWebMessage.html chromeWebView

When the page calls postMessage, the object parameter is converted to a JSON string and is posted asynchronously to the host process. This will result in the handler's Invoke method being called with the JSON string as a parameter.

\snippet ScenarioWebMessage.cpp WebMessageReceived

If the same page calls postMessage multiple times, the corresponding WebMessageReceived events are guaranteed to be fired in the same order. However, if multiple frames call postMessage, there is no guaranteed order. In addition, WebMessageReceived events caused by calls to postMessage are not guaranteed to be sequenced with events caused by DOM APIs. For example, if the page runs

chrome.webview.postMessage("message");
window.open();

then the NewWindowRequested event might be fired before the WebMessageReceived event. If you need the WebMessageReceived event to happen before anything else, then in the WebMessageReceived handler you can post a message back to the page and have the page wait until it receives that message before continuing.

interface ICoreWebView2
HRESULT
add_WebMessageReceived

Meta