Javascript 如何将内容脚本中的消息发送到Google Chrome扩展中的活动选项卡?
我是一个新手,创建了这个Chrome扩展,在将一条消息从内容脚本JS发送到我的边栏JS资源时遇到了一个问题,该资源被注入到一个网页中。这是我的manifest.json,在我使用的行下面,因为我不能使用Javascript 如何将内容脚本中的消息发送到Google Chrome扩展中的活动选项卡?,javascript,jquery,google-chrome-extension,Javascript,Jquery,Google Chrome Extension,我是一个新手,创建了这个Chrome扩展,在将一条消息从内容脚本JS发送到我的边栏JS资源时遇到了一个问题,该资源被注入到一个网页中。这是我的manifest.json,在我使用的行下面,因为我不能使用chrome.tabs.sendMessage: { "manifest_version": 2, "permissions": [ "tabs", "storage", "http://*/*&qu
chrome.tabs.sendMessage
:
{
"manifest_version": 2,
"permissions": [ "tabs", "storage", "http://*/*", "https://*/*" ],
"browser_action": {
"default_title": "Extension"
},
"background":{
"scripts": [ "jquery-3.5.1.min.js", "background.js"],
"persistent": false
},
"content_scripts":[
{
"matches": [ "http://*/*", "https://*/*" ],
"js": ["jquery-3.5.1.min.js", "content.js", "content-functions.js", "sidebar.js"]
}
],
"web_accessible_resources": [
"popup.html"
]
}
content.js:
chrome.runtime.sendMessage({ type: "pathChanged", value: filter });
chrome.runtime.onMessage.addListener(function(message, sender, sendResponse){
if(message.type == "pathChanged"){
$('#path').text(message.value);
}
})
问题是,所有选项卡都会收到此消息,并在我的侧边栏中更新此信息:
sidebar.js:
chrome.runtime.sendMessage({ type: "pathChanged", value: filter });
chrome.runtime.onMessage.addListener(function(message, sender, sendResponse){
if(message.type == "pathChanged"){
$('#path').text(message.value);
}
})
有趣的是,sidebar.js包含
chrome.tabs.sendMessage
,并且没有任何问题。那么,我如何将消息发送到侧边栏,但仅发送到活动选项卡?我肯定错过了什么,请帮我一把。使用基于端口的消息传递并反转方向:从iframe建立连接。iframe是一个chrome扩展://页面,因此它可以访问chrome
API,并可以查看它所属的选项卡
内容脚本:
let framePort;
chrome.runtime.onConnect.addListener(端口=>{
如果(port.name=='frame'){
//全局framePort可由将来运行的代码使用
framePort=端口;
port.postMessage({foo:'bar'});
}
});
//添加iframe元素并将其指向chrome.runtime.getURL('iframe.html')
//...........
iframe脚本:
chrome.tabs.getCurrent(tab=>{
const port=chrome.tabs.connect(tab.id,{name:'frame',frameId:0});
port.onMessage.addListener(msg=>{
如果(msg.foo=='bar'){
控制台日志(msg);
}
});
});
谢谢,工作很有魅力:)