WebView2Samples icon indicating copy to clipboard operation
WebView2Samples copied to clipboard

Javascript bridge window.external.notify

Open OzBob opened this issue 5 years ago • 4 comments

Add a sample demonstrating best practice to communicate events between the host and javascript both ways.

An messaging abstraction would benefit the WebView2 spec. There is a supported 'WebMessageReceived' API but is only from Host originated events which await a JS response.

The WebView2_spec says: "WebMessageReceived – Occurs when the content contained in the WebView2 control passes a string to the application by using JavaScipt." a sample showing how to send messages from JavaScript to the Native application hosting the WebView would be very useful.

"Win32 WebViewControl did not support ObjectForScripting or AddWebAllowedObject", @rjmurillo made a fine example of a necessary workaround to create a Javascript to Natvie notification 'JavaScriptBridge'.

It's basis was :

window.external.notify(event.data);

The browser MDN web docs on Window.external say it is deprecated. What would be the Chrome equivalent?

An iOS Safari webView compatible example: https://github.com/lovesunstar/WKBridge/blob/fb30c123e68b4dcd4c4a2a8087d7383dbac0afe9/Example/WKBridge/test.html

OzBob avatar Jun 25 '20 02:06 OzBob

Maybe related to issue 261 on 'feedback' repo: @shawty says: "I've worked out some interesting ways to get the javascript side of things communicating with the windows side of things"

OzBob avatar Jun 25 '20 03:06 OzBob

@OzBob - see my as yet unfinished project at : https://github.com/shawty/hbbtvbrowserEXPERIMENTAL there's plenty of sample code in there on how to use the message API's

shawty avatar Jun 25 '20 10:06 shawty

@shawty thank you. and an open issue about passing actual c# objects and JSON serialization using:

 await chrome.webview.hostObjects.sync.eventForwarder.SendData(dataObj);

here: https://github.com/MicrosoftEdge/WebViewFeedback/issues/292 which shows passing C# data objects without the JSON serialisation that your code uses https://github.com/shawty/hbbtvbrowserEXPERIMENTAL/blob/fae30f8e78a341254dc07d2f3bcb3c2f300d527e/EdgeWebView2Test/UtilClasses/PostMessageSender.cs#L10

I'm not sure C# to JS strongly typed data objects are a thing I can get behind, since I still need JS versions of those classes to get intellisense working in my JS/TS projects.

OzBob avatar Jun 29 '20 01:06 OzBob

2022 Feb 24 https://github.com/react-native-webview/react-native-webview/issues/1848#issuecomment-1040722767 [Webview2 Microsoft Windows] Implements postMessage and inject javascript in Webview2

So we are starting the party, again.

Just in time for the MAUI release in Build 2022 https://mybuild.microsoft.com/en-US/sessions/599c82b6-0c5a-4add-9961-48b85d9ffde0?source=/speakers/3737608b-5c9a-4422-b90e-ea325115dfb2 (about 20min in)

OzBob avatar Jun 03 '22 06:06 OzBob