I need to send postMessage from a Chrome app via webview to the homepage and vice versa.
I installed PostMessage from the Chrome app on the homepage, and PostMessage also got on the homepage, and the new one was sent back, but this PostMessage answer didn’t get into the Chrome app.
I see that this is possible in the Chrome API:
The guest will be able to send embed responses by sending event.source to the received message.
So the problem is that I can't get the Chrome app to catch the response from the home page, although I use event.source.postMessage ('', event.origin) to send the response. Is window.addEventListener ('message', messageHandler, false); at the end of background.js wrong?
I have my code below .:
background.js (where the Chrome app is initialized) .:
var myAppWin = null; var webview = null; chrome.app.runtime.onLaunched.addListener(function() { // Center window on screen. var screenWidth = screen.availWidth/2; var screenHeight = screen.availHeight; var chromeWindow = chrome.app.window.create('webview-embed.html', { id: "helloWorldID", bounds: { width: screenWidth, height: screenHeight, } }, function(win) { myAppWin = win; myAppWin.contentWindow.addEventListener('DOMContentLoaded', function() { webview = myAppWin.contentWindow.document.getElementById('webview'); try{ webview.addEventListener("contentload", function () { console.log("webview content is now loaded"); try{ console.log("Trying to post message"); webview.contentWindow.postMessage("Message from Chrome APP!", "*"); }catch(error){ console.log("postMessage error: " + error); } }); } catch(err) { console.log("Webview error: " + err); } }); }); //Event listnener for the PostMessage reply var messageHandler = function(event) { console.log("got message from page back: " + event.data); }; window.addEventListener('message', messageHandler, false); });
webview-embed.html (html file with webview tag) .:
<!DOCTYPE html> <head> <title>webview</title> </head> <body style='margin:0;padding:0;' > <webview src="http://localhost" style="width:100%;height:100%;" id="webview" ></webview> </body> </html>
index.html (homepage on the Internet that should catch the first PostMessage and send the response back to the Chrome app) .:
<!DOCTYPE html> <html lang="en" > <head> <meta charset="utf-8" /> <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1"> <title>title</title> </head> <body > <div id="wrapper" > //body </div> //Used to catch messages from the Chrome App and reply back var messageHandler = function(event) { console.log('Message received fom APP!'); try{ console.log(event); event.source.postMessage("Message from page", event.origin); console.log("Sent massage back to APP"); }catch(error){ console.log("Error on postMessage back to APP" + error); } }; window.addEventListener('message', messageHandler, false); </script> </body> </html>