CWebView::PostWebMessage Method  
 
BOOL PostWebMessage (
  LPCTSTR lpszMessage  
);

The PostWebMessage function posts a string or JSON message to the current page.

Parameters

lpszMessage
A null-terminated string which contains the message to be sent to the current page. This parameter cannot be NULL or an empty string.

Return Value

If the method succeeds, the return value is non-zero. If the method fails, the return value is zero. To get extended error information, call GetLastError.

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 WEBVIEW_OPTION_ENABLE_MESSAGES option is set, 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 GetWebMessage method.

Requirements

Minimum Desktop Platform: Windows 7 Service Pack 1
Minimum Server Platform: Windows Server 2008 R2 Service Pack 1
Header File: cstools12.h
Import Library: cshtmv12.lib
Unicode: Implemented as Unicode and ANSI versions

See Also