如何使用Chrome扩展API访问非活动选项卡的"文档"



我有一个在后台运行popup.js的chrome扩展,每次加载选项卡(chrome Tabs API(时,它都会执行一个名为replaceText.js的脚本

每次打开新选项卡时,都会为活动非活动动选项卡获取document。如何从其他选项卡访问document

popup.js

chrome.tabs.onUpdated.addListener( function (tabId, changeInfo, tab) {
if (changeInfo.status == 'complete' && tab.active) {
// console.log(tab.title, document);
chrome.tabs.executeScript(null, {
file: "replaceText.js"
}, function() {
// error
});
}
})

replaceText.js

let current_document = document;
// do something with document

manifest.json

{
"manifest_version": 2,
"name": "a name",
"description": "a description",
"version": "1.0",
"author": "an author",
"background": {
"scripts": ["popup.js"],
"persistent": true
},
"permissions": [
"tabs",
"http://*/",
"https://*/"
]
}

正如@wOxxOm所提到的,我需要用tabId替换null,这样脚本就可以知道在哪个选项卡中运行脚本,它默认为当前选项卡:tabs.executeScript docs。我还必须删除tab.active条件,这样它才能始终运行。

chrome.tabs.onUpdated.addListener( function (tabId, changeInfo, tab) {
if (changeInfo.status == 'complete') {
chrome.tabs.executeScript(tabId, {
file: "replaceText.js"
}, function() {
// error
});
}
})

最新更新