我是chrome-extension开发的新手。我按照了一些教程,后来我正在玩extension。有一些事情困扰我这个扩展。
重现的步骤:
是否有任何过滤器可以限制此项并且仅更改所点击页面上的按钮/文字?我知道这是因为background.js页面中的port.postMessage(message);
而发生的。
我找到了this,但我无法让它发挥作用。
任何帮助将不胜感激:)
答案 0 :(得分:2)
通讯方案很简单:
<强> devtools-panel.js 强>
var port = chrome.runtime.connect();
port.onMessage.addListener(message => {
$id('insertmessagebutton').innerHTML = message.content;
});
$id('executescript').onclick = () =>
runContentScript({code: "console.log('Content script executed')"});
$id('insertscript').onclick = () =>
runContentScript({file: "inserted-script.js"});
$id('insertmessagebutton').onclick = () => {
runContentScript({code: "document.body.innerHTML='<button>Send to panel</button>'"});
runContentScript({file: "messageback-script.js"});
};
function runContentScript(params) {
port.postMessage(
Object.assign({
tabId: chrome.devtools.inspectedWindow.tabId,
}, params)
);
}
function $id(id) {
return document.getElementById(id);
}
<强> background.js 强>
var tabPorts = {};
chrome.runtime.onConnect.addListener(port => {
let tabId;
port.onMessage.addListener(message => {
if (!tabId) {
// this is a first message from devtools so let's set the tabId-port mapping
tabId = message.tabId;
tabPorts[tabId] = port;
}
if (message.code || message.file) {
delete message.tabId;
chrome.tabs.executeScript(tabId, message);
}
});
port.onDisconnect.addListener(() => {
delete tabPorts[tabId];
});
});
chrome.runtime.onMessage.addListener((message, sender, sendResponse) => {
const port = sender.tab && tabPorts[sender.tab.id];
if (port) {
port.postMessage(message);
}
});
chrome.tabs.onRemoved.addListener(tabId => {
delete tabPorts[tabId];
});
chrome.tabs.onReplaced.addListener((newTabId, oldTabId) => {
delete tabPorts[oldTabId];
});