content_script 向 background 发消息要用:chrome.runtime.sendMessage
chrome.runtime.sendMessage({event: "xhr", data:option }, function (res) {
//option.onload(res);
//console.log(res);
if (res.event == "xhr" && !res.err){
option.onload(res);
}
});
background 接收消息:chrome.runtime.onMessage.addListener
javascript
chrome.runtime.onMessage.addListener(function (message, sender, sendResponse) {
if (message.event == "copy") {
//alert("copy detected");
//return true;
}
sendResponse({});
return true;
});
background 向 content_script 发消息要用:chrome.tabs.sendMessage
javascript
chrome.tabs.query({ active: true, currentWindow: true }, function(tabs) {
if (tabs && tabs.length > 0) {
const activeTab = tabs[0];
console.log('当前活动标签页的是:', activeTab);
try {
chrome.tabs.sendMessage(activeTab.id, {'evt':'mediaUrl','data':mediaUrl }, function (res) {
console.log(res);
});
} catch (error) {
console.error(error.message);
}
}
});
content_script 接收消息用:chrome.runtime.onMessage.addListener
和background中是一样的,注意其中的 sendResponse({});
这一句很关键,接收到了就要给一个回应;