如何使用 Chrome 扩展程序 API 访问未激活的选项卡的“文档”
How can I access the `document` of a tab that is not active using Chrome Extension API
我有一个在后台运行 popup.js
的 chrome 扩展程序,每次加载完一个选项卡时 (Chrome Tabs API) 它都会执行一个名为 replaceText.js
[ 的脚本=25=]
每次打开新标签时,replaceText.js
都会为 active 和 inactive 标签调用。但是,当我访问 document
时,它总是从 active 选项卡中获取 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 mentioned, I needed to replace null
with tabId so that the script could know in which tab to run the script, it defaults to the current tab: 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
});
}
})
我有一个在后台运行 popup.js
的 chrome 扩展程序,每次加载完一个选项卡时 (Chrome Tabs API) 它都会执行一个名为 replaceText.js
[ 的脚本=25=]
每次打开新标签时,replaceText.js
都会为 active 和 inactive 标签调用。但是,当我访问 document
时,它总是从 active 选项卡中获取 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 mentioned, I needed to replace null
with tabId so that the script could know in which tab to run the script, it defaults to the current tab: 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
});
}
})