How to communicate with WebView in Chrome App?

后端 未结 3 719
栀梦
栀梦 2021-01-06 17:07

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

3条回答
  •  盖世英雄少女心
    2021-01-06 17:37

    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);
      });
      

提交回复
热议问题