首先,请注意扩展中传递的消息是 JSON 序列化的。不可序列化类型(例如函数)不包含在消息中。
在内容脚本中,您必须将消息传递到后台页面,因为没有方法可以直接访问其他选项卡。
// Example: Send a string. Often, you send an object, which includes
// additional information, eg {method:'userdefined', data:'thevalue'}
chrome.extension.sendMessage(' ... message ... ');
In the 背景页, 使用chrome.tabs.query方法获取选项卡的 ID。为了简单起见,我对模式和 url 进行了硬编码。以这种方式包含上一条消息中的查询值可能是一个好主意:{query:{...}, data:...}
.
// background script:
chrome.extension.onMessage.addListener(function(details) {
chrome.tabs.query({
title: "title pattern",
url: "http://domain/*urlpattern*"
}, function(result) {
// result is an array of tab.Tabs
if (result.length === 1) { // There's exactely one tab matching the query.
var tab = result[0];
// details.message holds the original message
chrome.tabs.sendMessage(tab.id, details.message);
}
});
});
chrome.tabs.sendMessage用于将原始数据传递到不同的选项卡。
备注:在示例中,我仅在查询结果为一个唯一选项卡时才传递消息。当唯一性不是先决条件时,只需循环所有结果选项卡,使用result.forEach or:
for (var i=0, tab; i<result.length; i++) {
tab = results[i];
...
}