How to communicate with WebView in Chrome App?

后端 未结 3 699
栀梦
栀梦 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条回答
  •  Happy的楠姐
    2021-01-06 17:22

    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:

    // Initialize communications
    webView.contentWindow.postMessage('hello, webpage!', 'https://your.web.page/*');
    addEventListener('message', function(e) {
    
        // I expect this check to work, but I have not tested it.
        if (e.source != webView.contentWindow)
            return;
    
        // Handle e.data however you want.
    });
    

    In the web page:

    var messageSource, messageOrigin;
    addEventListener('message', function(e) {
        if (!messageSource) {
    
            /*
             * Once we have a messageSource, we should not allow anybody to change
             * messageSource again
             */
    
            if (e.data == "hello, webpage!") {
    
                /*
                 * If possible, you should validate the `e.origin` value here. It could 
                 * possibly come from somewhere else. However, this is quite safe as it 
                 * stands, since there only is a very narrow time window where the app 
                 * is open willing to accept the "hello, webpage!" message.
                 *
                 * Another way of validating, is by having the app wait for the 
                 * "hello, host!" message. If that response is not received within a second
                 * the app host could simply reload the app.
                 */
    
                messageSource = e.source;
                messageOrigin = e.origin;
                messageSource.postMessage("hello, host!", messageOrigin);
            }
        } else {
            // Handle messages however you like. This will simply respond to every message:
            messageSource.postMessage('Your message: ' + e.data, messageOrigin);
        }
    });
    

提交回复
热议问题