我试图将标签重定向到http://google.com
,每隔几分钟,无论标签发生了什么(当然它仍然打开)。
我正在使用:
setTimeout(function() {
window.location.href = "http://google.com";
}, 500000);
然而,只要我在标签页中加载新页面,计数器就会刷新 有没有办法设置标签的全局时间倒计时,这样无论我加载什么,我仍然会每隔几分钟重定向一次?
答案 0 :(得分:1)
在页面加载之间保持计时器的一种方法是使用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);
行注释掉。但是,如果你这样做,事情可能会让人感到困惑。