是否可以使用 chrome.tabs.sendmessage 从内容脚本向后台页面发送消息?
Is it possible to send a message from a Content Script to a Background Page using chrome.tabs.sendmessage?
我找到了很多关于将消息从后台页面发送到内容脚本的示例和文档,但我无法找到一种方法将消息从内容脚本发送到后台页面。
原因是我想用chrome.downloader.download
,例如
chrome.downloads.download({
"url": randomImageForSpotCheck
}, function () {...
spotcheck(randomImage);
});
第一个 google 搜索出现:
Sending a request from a content script looks like this:
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 ^^
});
我找到了很多关于将消息从后台页面发送到内容脚本的示例和文档,但我无法找到一种方法将消息从内容脚本发送到后台页面。
原因是我想用chrome.downloader.download
,例如
chrome.downloads.download({
"url": randomImageForSpotCheck
}, function () {...
spotcheck(randomImage);
});
第一个 google 搜索出现:
Sending a request from a content script looks like this:
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 ^^
});