是否可以使用chrome.tabs.sendmessage从内容脚本向背景页面发送消息?

时间:2015-02-26 18:25:32

标签: javascript google-chrome-extension

我找到了大量关于从后台页面向内容脚本发送消息的示例和文档,但是无法找到将消息从内容脚本发送到后台页面的方法。

原因是我想使用chrome.downloader.download,例如

chrome.downloads.download({
        "url": randomImageForSpotCheck
    }, function () {...
       spotcheck(randomImage);
});

1 个答案:

答案 0 :(得分:3)

首次谷歌搜索出现:

  

从内容脚本发送请求如下所示:

chrome.runtime.sendMessage({greeting: "hello"}, function(response) {  
  console.log(response.farewell);  
});  

(here)

在你的后台脚本中,你应该有一些代码来监听这样的消息:

chrome.runtime.onMessage.addListener(
  function(request, sender, sendResponse) {
    if (sender.tab) {
        // is from content script
        // access stuff like:
        //   request.horseradish
        sendResponse({});
    }
});

您的内容脚本可以发送消息:

//                          vv put whatever data you want here
chrome.runtime.sendMessage({horseradish: true}, function(response) {  
  // this is a callback function to execute,
  // response is the object sent by your sendResponse({});
  //                                     this one     ^^
});  
相关问题