我是编写扩展(和 JavaScript)的新手。我想要一个扩展程序在打开/刷新某个 URL 时在计时器上运行。代码如下。这是我迄今为止在网上找到的所有内容。我不确定这是否一次只运行一个选项卡。
list .json
{
"manifest_version": 2,
"name": "Test Plugin",
"description": "This extension is a test.",
"version": "1.0",
"content_scripts": [
{
"matches": ["https://www.google.com/*"],
"js": ["main.js"]
}
],
"permissions": [
"activeTab"
]
}
main.js
chrome.tabs.onUpdated.addListener( function (tabId, changeInfo, tab) {
if (changeInfo.status == 'complete' && tab.active) {
setInterval(mainF, 5000)
}
})
function mainF() {
var getTitle = document.getElementById('title');
var titleValue = getTitle.Value();
var fso = new ActiveXObject("Scripting.FileSystemObject");
var fh = fso.OpenTextFile("test.txt", 8, false, 0);
fh.WriteLine(titleValue);
fh.Close()
}
最佳答案
将您的逻辑移至 Event Page .
Content Script无法访问 chrome.tabs
API。
根据best practices when using event pages ,
Use event filters to restrict your event notifications to the cases you care about. For example, if you listen to the
tabs.onUpdated
event, try using the webNavigation.onCompleted event with filters instead (the tabs API does not support filters). That way, your event page will only be loaded for events that interest you.
代码片段看起来像
list .json
{
"manifest_version": 2,
"name": "Test Plugin",
"description": "This extension is a test.",
"version": "1.0",
"background": {
"scripts": ["main.js"],
"persistent": false
},
"permissions": [
"webNavigation"
]
}
main.js
chrome.webNavigation.onCompleted.addListener(function(details){
console.log("Certain url with hostSuffix google.com has been loaded");
}, {url: [{hostSuffix: 'google.com'}]});
关于javascript - 页面加载/刷新时在后台运行扩展,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36682603/