我正在开发一个浏览器扩展,即使在后台自动刷新后,该扩展也需要一直运行。问题在于,页面会随机自动卸载,而脚本只是关闭。我需要找到一种始终保持内容脚本运行的方法。这是代码的一部分:
// content.js:
function run(fn) {
if(typeof(Worker) !== "undefined") {
if(typeof(w) == "undefined") {
w = new Worker(URL.createObjectURL(new Blob(['('+fn+')()'])));
}
w.onmessage = function(event) {
if (isNaN(grabbedmin) && ID) {
bump() // Note: the bump function refreshes in the page.
w.terminate();
}
if ($("[href='/server/bump/" + ID + "']").text().includes("Bump")) {
bump()
w.terminate();
}
document.getElementById("bumpcount").innerHTML = "Autobumper Enabled: " + getCurrentTimestamp();
if (numberwow == grabbedmin) {
bump()
w.terminate();
}
};
}
}
上面的代码基本上由该工作人员每分钟运行一次:
// content.js:
const worker = run(function() {
var i = 0;
function timedCount() {
i = i + 1;
postMessage(i);
setTimeout(function(){timedCount()},1000);
}
timedCount();
});
background.js是否有办法在应有的状态下检测到content.js未运行(或页面已卸载),然后重新加载它?
注意:您可以在这里找到脚本:https://github.com/Theblockbuster1/disboard-auto-bump
[浏览docs并查看示例后,我将其放在一起:
chrome.tabs.query({
url: ["*://disboard.org/*dashboard/servers", "*://disboard.org/*dashboard/servers/"] // finds matching tabs
}, function(tabs) {
tabs.forEach(tab => {
chrome.tabs.update(tab.id,{autoDiscardable:false});
});
});
chrome.tabs.onUpdated.addListener(function(tabId, changeInfo, tab) {
// checks if the tab somehow got discarded and notifies the user:
if (changeInfo.discarded == true) chrome.notifications.create('', {
title: 'Looks like the tab got discarded.',
message: "(that wasn't supposed to happen...) Return to the tab to resume.",
contextMessage: 'oops...',
iconUrl: '/disboard-auto-bump-logo.png',
requireInteraction: false,
type: 'basic'
});
// checks if the browser automatically re-enabled autoDiscarding and disables it
if (changeInfo.autoDiscardable == true) chrome.tabs.update(tabId,{autoDiscardable:false});
});