更新时间:2023-12-05 08:51:22
通常没有直接的方法来访问不同来源的 window
对象.如果您想在不同框架中的内容脚本之间安全通信,您必须向后台页面发送一条消息,后台页面又将消息发送回选项卡.
There's generally no direct way of accessing a different-origin window
object. If you want to securely communicate between content scripts in different frames, you have to send a message to the background page which in turn sends the message back to the tab.
这是一个例子:
manifest.json
的一部分:
"background": {"scripts":["bg.js"]},
"content_scripts": [
{"js": ["main.js"], "matches": ["<all_urls>"]},
{"js": ["sub.js"], "matches": ["<all_urls>"], "all_frames":true}
]
main.js
:
var isTop = true;
chrome.runtime.onMessage.addListener(function(details) {
alert('Message from frame: ' + details.data);
});
sub.js
:
if (!window.isTop) { // true or undefined
// do something...
var data = 'test';
// Send message to top frame, for example:
chrome.runtime.sendMessage({sendBack:true, data:data});
}
后台脚本'bg.js':
Background script 'bg.js':
chrome.runtime.onMessage.addListener(function(message, sender) {
if (message.sendBack) {
chrome.tabs.sendMessage(sender.tab.id, message.data);
}
});
另一种方法是使用 bg.js
中的 chrome.tabs.executeScript
来触发主内容脚本中的函数.
An alternative method is to use chrome.tabs.executeScript
in bg.js
to trigger a function in the main content script.