Description
Sends the web message in the JSON format to the top-level document in WebBrowser asynchronously. In the top-level document of WebBrowser, the message can be subscribed or unsubscribed through the following JavaScript:
window.chrome.webview.addEventListener('message', handler)
window.chrome.webview.removeEventListener('message', handler)
"handler" is the process of handling specific events. The event args is an instance of MessageEvent defined in the HTML5 specification. The event args data property is the JSON string sent by this function PostJsonWebMessage, and the JSON string has been parsed into the corresponding JavaScript object. If a navigation occurs before the message reaches the page, the message will be discarded. This function will trigger the WebMessageReceived event.
Here is a JavaScript code example:
window.chrome.webview.addEventListener('message', arg => { if ("SetColor" in arg.data) { document.getElementById("colorable").style.color = arg.data.SetColor; } if ("WindowBounds" in arg.data) { document.getElementById("window-bounds").value = arg.data.WindowBounds; } }); function SetTitleText() { let titleText = document.getElementById("title-text"); window.chrome.webview.postMessage(`SetTitleText ${titleText.value}`); } function GetWindowBounds() { window.chrome.webview.postMessage("GetWindowBounds"); }
Applies to
Syntax
objectname.PostJsonWebMessage (sring json)
Argument |
Description |
---|---|
controlname |
The name of the WebBrowser control. |
json |
The message (in JSON format) to be sent to the top-level document, for example: "{\"a\": \"b\"}" "1.2" "\"example\"" |
Return value
Integer.
Returns values as follows. If any argument's value is null, the method returns null.
-
1 -- Success
-
-1 -- Failed to execute the line.
-
-2 -- Failed to initialize the control and obtain the WebBrowser object. The WebView2 is invalid.
-
-4 -- The target path does not exist.
-
-5 -- The URI is invalid.
-
-6 -- The specified download task does not exist.
-
-8 -- The setting item does not exist.
-
-9 -- The path is invalid or does not exist.
-
-11 -- Unknown error.
-
-12 -- Invalid event name.
-
-14 -- Invalid argument.
-
-15 -- Failed to create screenshot file.
-
-16 -- There is a print job in progress, which cannot be closed.
-
-17 -- Could not find the corresponding item.
Examples
This example sends the specified web message in JSON format to the top-level document to set the color:
//window.chrome.webview.addEventListener('message', arg => { // window.chrome.webview.postMessage(JSON.stringify(arg.data)); // }); Integer li_return li_return = wb_1.PostJsonWebMessage('{"SetColor":"blue"}')
See also