[英]How to set a persistent global timeout using a Tampermonkey/Greasemonkey script?
I am trying to redirect the tab to, say, http://google.com
every few minutes, no matter what happened to the tab (it is still open of course). 我试图每隔几分钟将选项卡重定向到
http://google.com
,无论该选项卡发生了什么(当然它仍然处于打开状态)。
I am using: 我在用:
setTimeout(function() {
window.location.href = "http://google.com";
}, 500000);
However the counter refreshes as soon I load a new page in the tab. 但是,计数器会在我在选项卡中加载新页面后刷新。
Is there a way to set a global time countdown for the tab so that no matter what I load, I still get redirected every few minutes? 有没有一种方法可以设置选项卡的全局时间倒数,以便无论加载什么,我仍然每隔几分钟重定向一次?
One way to persist the timer between page loads is to use GM_setValue()
Doc . 在页面加载之间保留计时器的一种方法是使用
GM_setValue()
Doc 。
Here's a complete Tampermonkey/Greasemonkey script that illustrates the process: 这是说明该过程的完整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";
}
}
}
Depending on your intentions, you may wish to comment out the checkElapsedAndPossiblyRedirect (true);
根据您的意图,您可能希望注释掉
checkElapsedAndPossiblyRedirect (true);
line. 线。 But, things could get confusing if you do.
但是,如果您这样做,可能会造成混乱。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.