I'm trying to pass the FCM data from dart to the webview using postMessage and listen to these messages in ReactJS.
ReactJS:
window.addEventListener("message", () => {});
Flutter:
webViewController.runJavascript('window.postMessage("Hello ReactJS")');
Unfortunately, no events going through to ReactJS. Does someone have an idea how to use postMessage with webview_flutter?
UPDATED
WebView(
initialUrl: '<WEB_URL>',
onPageStarted: (url) {
setState(() {
loadingPercentage = 0;
});
},
onProgress: (progress) {
setState(() {
loadingPercentage = progress;
});
},
onPageFinished: (url) {
setState(() {
loadingPercentage = 100;
});
},
onWebViewCreated: (WebViewController controller) {
webViewController = controller;
Future.delayed(Duration(seconds: 5), () {
print('JETZT');
JavaScriptHelper.postMessage({'action': 'FCM_OPENED'});
});
},
debuggingEnabled: true,
javascriptMode: JavascriptMode.unrestricted,
),
JavaScriptHelper:
class JavaScriptHelper {
static postMessage(Map<String, dynamic> data) async {
try {
print(json.encode(data));
await webViewController?.runJavascript(
'window.postMessage(${json.encode(data)})',
);
} catch (err) {
print(err);
}
}
}
That was a thinking mistake on my side. The runJavascript method really executes the command in the Webview javascript therefore there is no window.postMessage because there is no iframe.
I managed it the following way:
Flutter:
controller.runJavascript('window.fromFlutter("Hello ReactJS")');
ReactJS:
(In App.tsx, but over render component)
(window as any).fromFlutter = function(data) {
alert("This is working now!!!");
alert(data);
}