![](/img/trans.png)
[英]Communicate between scripts in the background context (background script, browser action, page action, options page, etc.)
[英]Communicate between content script and options page
我已经看到很多问题,都是关于背景页面到内容脚本的。
我的扩展程序有一个选项页面和一个内容脚本。 内容脚本处理存储功能( chrome.storage
操作)。 每当用户更改选项页面中的设置时,我都想向内容脚本发送一条消息以存储新数据。
选项.js
var data = "abcd"; // let data
chrome.tabs.query({ active: true, currentWindow: true }, function (tabs) {
chrome.tabs.sendMessage(tabs[0].id, "storeData:" + data, function(response){
console.log(response); // gives undefined :(
});
});
内容脚本js
chrome.runtime.onMessage.addListener(function(request, sender, sendResponse) {
// not working
});
1)为什么这种方法不起作用?
您正在尝试向自己发送消息: chrome.tabs.query({ active: true, currentWindow: true }, ...);
返回了您正在执行某些操作的选项页面chrome.tabs.query({ active: true, currentWindow: true }, ...);
2)此程序是否有其他(更好的)方法。
这取决于您尝试向哪个页面发送消息。 您可以只向所有页面发送消息:使用空过滤器查询并迭代结果。
您可以使用内容脚本跟踪最后一个活动选项卡,但这听起来过于复杂。
或者,您可以使用对chrome.storage
更改在所有扩展上下文中生成onChanged
事件这一事实。 如果您修改保存在chrome.storage
选项,您的内容脚本可以侦听onChanged
事件并根据需要重新处理它们的数据,这样您就可以完全跳过消息传递。
精准匹配模式:
{ currentWindow: true, url: 'http://127.0.0.1/*' }
选项页面
chrome.tabs.query({ currentWindow: true, url: 'http://127.0.0.1/*' }, tabs => {
chrome.tabs.sendMessage(tabs[0].id, 'popup-tabs send a message');
});
内容脚本
chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {
console.log('request: ', request);
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.