PostWebMessage Method  
 

Sends a JSON-formatted message from the host application to scripts running inside the browser.

Syntax

object.PostWebMessage( Message )

Parameters

Message
A string which contains the message to be sent to the current page.

Return Value

Returns True if the method succeeds or False if the method fails.

Remarks

The PostWebMessage method sends a message from the host application to the currently loaded page using the WebView2 messaging channel. The call is asynchronous: if it is invoked from a thread other than the thread that created the browser instance, the method marshals the request to the UI thread and returns immediately, with delivery performed later on that thread. Internally, this posts a private window message to the host window; when handled, it forwards the text using the ICoreWebView2::PostWebMessageAsString method.

For a page to receive messages from the host, web messaging must be enabled. When the AllowMessages property is True, the wrapper enables web messages in the control settings (exposing window.chrome.webview to the script) and wires the corresponding message events. If this option is not enabled, the page will not see the messaging object and cannot receive messages.

On the JavaScript side, the page subscribes to messages using the standard listener pattern. Messages posted with this method are delivered as strings to the page's handler:

 window.chrome.webview.addEventListener('message', (event) => {
  // event.data is the string posted by WebViewPostWebMessage
  const text = event.data;
  // If you know the string is JSON, you can parse it explicitly
  // const obj = JSON.parse(text);
}); 

Because delivery is asynchronous, there is no built-in acknowledgement and ordering is not guaranteed across navigations. If the page navigates or reloads after you call PostWebMessage, a listener registered on the previous document will not receive later messages.

Messages are Unicode strings and you should avoid sending very large payloads. For large data transfers, consider using application-level protocols rather than embedding large content in a single message. This method is primarily intended to enable your host application to notify the web page the user has taken some action which should be reflected in the browser. The web page can send messages back to your application using window.chrome.webview.postMessage(value) and you can receive those messages using the MessageReceived event.

See Also

AllowMessages Property, MessageReceived Event