javascript - 如何使用 Tampermonkey/Greasemonkey 脚本设置持久的全局超时?

标签 javascript jquery greasemonkey tampermonkey

我试图每隔几分钟将标签页重定向到例如 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/

相关文章:

javascript - 多个 JavaScript 函数的作用域

javascript - 将数据从一个 Controller 传递到另一个 Controller 以重定向到 View

用于动画边框半径的 jQuery

javascript - 将标签添加到标签内的文本

javascript - 使用 Greasemonkey 2.0 绑定(bind)到 Firefox 30 中的 unsafeWindow 事件

javascript - 经验丰富的 Javascript 开发人员的 Greasemonkey 指南?

javascript - 如何用新的替换我的网格

javascript - 如何添加 notyjs 短信的链接

javascript - Highcharts:饼图标签重叠

javascript - ajaxStart 不适用于 onclick