Search code examples
javascriptjquerygreasemonkeytampermonkey

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).

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?


Solution

  • One way to persist the timer between page loads is to use GM_setValue()Doc.

    Here's a complete Tampermonkey/Greasemonkey script that illustrates the process:

    // ==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); line. But, things could get confusing if you do.