[英]How to send message from Content Script to Active Tab in Google Chrome Extension?
我是一個新手,正在創建這個 Chrome 擴展程序,並且在將消息從 Content Script JS 發送到我的側邊欄 JS 資源時遇到問題,該資源被注入到 web 頁面中。 這是我的manifest.json和我使用的行下方,因為我不能使用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"
]
}
內容.js:
chrome.runtime.sendMessage({ type: "pathChanged", value: filter });
問題在於所有選項卡都會收到此消息並在我的側邊欄中更新此信息:
側邊欄.js:
chrome.runtime.onMessage.addListener(function(message, sender, sendResponse){
if(message.type == "pathChanged"){
$('#path').text(message.value);
}
})
有趣的事實是 sidebar.js 包含chrome.tabs.sendMessage
並且沒有問題。 那么我如何將消息發送到我的側邊欄但只發送到活動選項卡? 我一定是錯過了什么,請幫幫我。
使用基於端口的消息傳遞並反轉方向:從 iframe 建立連接。 iframe 是一個 chrome-extension:// 頁面,因此它可以訪問chrome
API 並且可以查看它屬於哪個選項卡。
內容腳本:
let framePort;
chrome.runtime.onConnect.addListener(port => {
if (port.name === 'frame') {
// global framePort can be used by code that will run in the future
framePort = port;
port.postMessage({foo: 'bar'});
}
});
// add iframe element and point it to 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 => {
if (msg.foo === 'bar') {
console.log(msg);
}
});
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.