我试图每隔几分钟将标签页重定向到例如 http://google.com
,无论标签页发生了什么(当然它仍然是打开的)。
我正在使用:
setTimeout(function() {
window.location.href = "http://google.com";
}, 500000);
然而,只要我在选项卡中加载新页面,计数器就会刷新。
有没有办法为选项卡设置全局时间倒计时,这样无论我加载什么,我仍然每隔几分钟就会被重定向一次?
最佳答案
在页面加载之间保持计时器的一种方法是使用 GM_setValue()
Doc .
这是一个完整的 Tampermonkey/Greasemonkey 脚本,它说明了这个过程:
// ==UserScript==
// @name _Persistent redirect timer
// @include http://YOUR_SERVER.COM/YOUR_PATH/*
// @grant GM_getValue
// @grant GM_setValue
// ==/UserScript==
var timerLength = 500000; //- 500,000 milliseconds
var timerStart = GM_getValue ("timerStartKey");
if (timerStart)
timerStart = JSON.parse (timerStart);
else
resetTimerStart ();
/*-- RECOMMENDED: If too much time has passed since the last page load,
restart the timer. Otherwise it will almost instantly jump to the
redirect page.
*/
checkElapsedAndPossiblyRedirect (true);
console.log ("timerStart: ", timerStart);
//-- Polling every 10 seconds is plenty
setInterval (checkElapsedAndPossiblyRedirect, 10 * 1000);
function resetTimerStart () {
timerStart = new Date().getTime ();
GM_setValue ("timerStartKey", JSON.stringify (timerStart) );
}
function checkElapsedAndPossiblyRedirect (bCheckOnly) {
if ( (new Date().getTime() ) - timerStart >= timerLength) {
resetTimerStart ();
if ( ! bCheckOnly) {
console.log ("Redirecting.");
window.location.href = "http://google.com";
}
}
}
根据您的意图,您可能希望注释掉 checkElapsedAndPossiblyRedirect (true);
行。但是,如果这样做,事情可能会变得困惑。
关于javascript - 如何使用 Tampermonkey/Greasemonkey 脚本设置持久的全局超时?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30652388/