Javascript 如何使脚本从chrome扩展一直在后台运行?
我最近创建了我的第一个谷歌浏览器扩展。这很有效,但我想让它变得更好。Javascript 如何使脚本从chrome扩展一直在后台运行?,javascript,google-chrome,google-chrome-extension,Javascript,Google Chrome,Google Chrome Extension,我最近创建了我的第一个谷歌浏览器扩展。这很有效,但我想让它变得更好。 我的扩展的目标是能够在特定时间刷新页面。我可以这样做,但当我离开扩展弹出窗口时,它会取消我设置的“计时器”。 在这里您可以找到一些代码: Popup.html 复习 这是一个自动的页面 H M s 程序员刷新 在未来的日子里,你将为我们的未来而奋斗 Popup.js: console.log("popup.js loaded") document.addEventListener('DOMConte
我的扩展的目标是能够在特定时间刷新页面。我可以这样做,但当我离开扩展弹出窗口时,它会取消我设置的“计时器”。
在这里您可以找到一些代码:
Popup.html
复习
这是一个自动的页面
H
M
s
程序员刷新
在未来的日子里,你将为我们的未来而奋斗
Popup.js:
console.log("popup.js loaded")
document.addEventListener('DOMContentLoaded', function () {
if(document.getElementById("input-hour") != null){
var input_h = document.getElementById("input-hour");
input_h.value = localStorage.getItem("hour_value");
}
if(document.getElementById("input-min") != null){
var input_m = document.getElementById("input-min");
input_m.value = localStorage.getItem("min_value");
}
if(document.getElementById("input-sec") != null){
var input_s = document.getElementById("input-sec");
input_s.value = localStorage.getItem("sec_value");
}
if(document.getElementById("ss_button") != null){
var ss_button = document.getElementById("ss_button");
ss_button.addEventListener('click', ss_clickHandler);
}
function ss_clickHandler(e) {
localStorage.setItem("hour_value", input_h.value);
localStorage.setItem("min_value", input_m.value);
localStorage.setItem("sec_value", input_s.value);
refresh_hour = parseInt(input_h.value);
refresh_min = parseInt(input_m.value);
refresh_sec = parseInt(input_s.value);
countdown(refresh_hour, refresh_min, refresh_sec);
function countdown(hours, minutes, seconds){
var now = new Date();
var then = new Date();
var onesecond = new Date(1970, 0, 1, 1, 0, 1, 0);
if(now.getHours() > hours ||
(now.getHours() == hours && now.getMinutes() > minutes) ||
now.getHours() == hours && now.getMinutes() == minutes && now.getSeconds() >= seconds) {
then.setDate(now.getDate() + 1);
}
then.setHours(hours);
then.setMinutes(minutes);
then.setSeconds(seconds);
var timeout = (then.getTime() - now.getTime() - onesecond.getTime());
setTimeout(function() { chrome.runtime.sendMessage({message: "reload"}); }, timeout);
}
}
});
最后是background.js:
chrome.runtime.onMessage.addListener( function(request,sender,sendResponse) {
if( request.message === "reload" ) {
chrome.tabs.getSelected(null, function(tab) {
var code = 'window.location.reload(true);';
chrome.tabs.executeScript(tab.id, {code: code});
});
}
});
谁能帮帮我吗?
提前谢谢 退出弹出窗口后,popup.html中的脚本将被删除,因此无法将间隔代码放在那里 默认情况下,background.js是持久性的,但请确保manifest.json没有将持久性覆盖为false
由于background.js现在是持久性的,您可以创建一个setInterval(或任何类型的interval函数),为所有要刷新的选项卡向content.js发送消息。这是否回答了您的问题?大多数浏览器都会停止非活动选项卡的几乎所有资源