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

Is it possible to send a message from a Content Script to a Background Page using chrome.tabs.sendmessage?

本文关键字:背景 脚本 消息 可以使 chrome tabs sendmessage 是否      更新时间:2024-06-28

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

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

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

第一次谷歌搜索出现:

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

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

(此处)

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

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