从chrome扩展程序到网页的通信

时间:2017-04-20 21:57:45

标签: javascript google-chrome google-chrome-extension

我知道可以将网页中的消息转发到Chrome扩展程序并获得回复网页的确认响应,但是可能反过来吗?

我的问题 "我需要能够将请求发送到网页并等待我可以在扩展程序中使用的响应。也许没有postMessage?"

我知道文档说"只有网页可以启动连接。" (https://developer.chrome.com/extensions/messaging#external-webpage

我想要尝试这样的票价。

background.js

chrome.extension.sendMessage("Hello from extension to webpage");
window.postMessage("Hello from extension to webpage");
chrome.tabs.sendMessage(TAB_ID, "Hello from extension to webpage");

webpage.js(不属于扩展名)

window.onmessage = (event) => {
  // Waiting for that message.
  console.info("Event received ", event);
}
window.chrome.runtime.connect(CHROME_EXTENSION_APP_ID).onMessage.addListener(function (){
  function(request, sender, sendResponse) {
     console.info("Event received from the extension", event);
  }
})  

任何想法都将受到赞赏:)

1 个答案:

答案 0 :(得分:0)

您可以使用chrome.tabs.executeScript API执行此操作。

        var dataToWebPage = {text: 'test', foo: 1, bar: false};
        chrome.tabs.executeScript({
            code: '(' + function(params) {
                //This function will  work in webpage
                console.log(params); //logs in webpage console 
                return {success: true, response: "This is from webpage."};
            } + ')(' + JSON.stringify(dataToWebPage) + ');'
        }, function(results) {
            //This is the callback response from webpage
            console.log(results[0]); //logs in extension console 
        });

请注意,它需要标签 permission