在Chrome浏览器中,背景脚本可以使用chrome.runtime.sendMessage()
方法来向内容脚本或其他扩展组件发送消息。这个方法可以发送多个消息,只需要在调用sendMessage()
方法时,多次调用即可。
以下是一个示例代码:
background.js:
// 向内容脚本发送多个消息
chrome.runtime.onMessage.addListener(function(message, sender, sendResponse) {
if (message.action === 'sendMultipleMessages') {
// 发送多个消息
chrome.tabs.sendMessage(sender.tab.id, {text: 'Message 1'});
chrome.tabs.sendMessage(sender.tab.id, {text: 'Message 2'});
chrome.tabs.sendMessage(sender.tab.id, {text: 'Message 3'});
}
});
content.js:
// 接收消息
chrome.runtime.onMessage.addListener(function(message, sender, sendResponse) {
console.log(message.text);
});
在上述示例中,背景脚本background.js
监听chrome.runtime.onMessage
事件,当收到消息{action: 'sendMultipleMessages'}
时,会向当前活动标签页的内容脚本发送三个不同的消息。
内容脚本content.js
通过监听chrome.runtime.onMessage
事件来接收消息,并将接收到的消息内容打印到控制台。
这样,当在扩展的其他部分(例如popup页面)调用chrome.runtime.sendMessage({action: 'sendMultipleMessages'})
时,就会触发背景脚本向内容脚本发送三个不同的消息。
请注意,为了使背景脚本能够向内容脚本发送消息,需要在manifest.json
文件中的permissions
字段中添加"tabs"
权限。
下一篇:背景脚本和内容脚本之间的通信问题