I have developed a website which I intend to display inside a webview, within a Chrome App. This works fine.
Now, I want to use postMessage from the website, to send messages out of the webview and into the containing Chrome App. This is done via top.postMessage
inside the webview.
I've tried the following event listeners:
webView.contentWindow.addEventListener('message', messageHandler);
webView.addEventListener('message', messageHandler);
window.addEventListener('message', messageHandler);
document.addEventListener('message', messageHandler);
I have successfully implemented the following event listeners. All of which work as expected: contentload
, dialog
and consolemessage
.
Unless I can get this to work, I am considering using consolemessage
to send messages from the webview to the container - something I find unappealing, and I suspect it won't work when not using the developer mode.
The reason that the embedded web page is unable to post messages to the app, is because the embedded web page does not have a reference to the app.
top.postMessage
is not a reference to the app.top
would work if you were trying to access the topmost frame, within the same webview.To be able to send messages to the app, the web page needs a reference to the app. The easiest way to do this, is by having the app send the first message to the frame - a "hello"-message.
From the app:
In the web page:
The webview sample has a good demo of using postMessage to send messages between an app and an external page loaded in a webview.
Here are the key pieces of code.
In the app, listen to the
loadstop
event of the webview and send an initial message to the page. You can restrict this message to specific domains or pages.In the external page, listen for the
message
event and save off the source and origin.Then the page can use those objects to post a message back to the app.
The app should also listen to the
message
event to receive the messages from the external page.In the guest page inside the contained webview, use
chrome.runtime.sendMessage()
to send messages to the containing app.In the app, use
chrome.runtime.onMessage.addListener()
to listen to those messages.Note that you can message any app this way, not only the one containing your webview, but you'll need to know the app's ID for that, and use
onMessageExternal
instead ofonMessage
. For the containing app, the ID is optional.Here's a working example of this mechanism. It's a Polymer element, but that doesn't change the mechanism:
designerProxy_
is the equivalent of your guest page;registerDesignerProxyListener_
is the equivalent of your app.