How to communicate with WebView in Chrome App?

frodeborli picture frodeborli · May 21, 2015 · Viewed 11.1k times · Source

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.

Answer

Sarah Elan picture Sarah Elan · May 21, 2015

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.

  1. 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.

    wv1.addEventListener('loadstop', sendInitialMessage);
    
    function sendInitialMessage(e) {
     // only send the message if the page was loaded from googledrive hosting
     e.target.contentWindow.postMessage("initial message", "https://googledrive.com/host/*");
    }
    
  2. In the external page, listen for the message event and save off the source and origin.

    window.addEventListener('message', onMessage);
    
    var appWindow, appOrigin;
    
    function onMessage(e) {
     appWindow = e.source;
     appOrigin = e.origin;
    }
    

    Then the page can use those objects to post a message back to the app.

    function doSendMessage() {
     if (appWindow && appOrigin) {
      appWindow.postMessage("this is a message from the page!", appOrigin);
     } 
    }
    
  3. The app should also listen to the message event to receive the messages from the external page.

    window.addEventListener('message', function(e) {
     log("[???] messagereceived: " + e.data);
    });