Hack 41. Refresh Pages Automatically

 < Day Day Up > 

Reload selected pages every 20 minutes.

Although it's not generally considered "friendly" behavior, there are several reasons why you might want to have some pages refresh themselves automatically. One is simply to keep an eye on the latest news. Another is to keep your login sessions alive longer, on sites that log you out after a period of inactivity.

Greasemonkey allows a lot of freedom, and many user scripts abuse it and behave badly. I recommend moderation and common sense when creating additional load on other people's web servers. A delay of 20 minutes seems reasonable, so that's the default I used for this script.

5.3.1. The Code

This is one of the simplest user scripts you can imagine. When it executes, it sets a timer to call a function after a delay. The function in this case is document.location.reload, which reloads the page.

Technically, timers are not threads; they simply interrupt whatever is executing at the time. But they are the closest thing to multithreading in JavaScript. You will see setTimeout and its cousin setInterval in many scripts that animate the user interface.


The multiplying factor, 60*1000, converts the timeout delay from minutes to milliseconds, as required by the setTimeout function.

Although it's ignored in this script, setTimeout has a return value: the ID for the timer that was set. With this ID, it is possible to cancel the timer by calling clearTimeout.


Save the following user script as autoreload.user.js:

 // ==UserScript== // @name Auto Reload // @namespace http://blog.monstuff.com/archives/cat_greasemonkey.html // @description Reload pages every 20 minutes // @include http://slashdot.org/ // @include http://www.slashdot.org/ // ==/UserScript== // based on code by Julien Couvreur // and included here with his gracious permission var numMinutes = 20; window.setTimeout("document.location.reload();", numMinutes*60*1000); 

5.3.2. Running the Hack

Before installing this script, configure the URLs that you want to reload automatically. You can do this by editing the script, or by adding URLs in the install dialog. Slashdot (http://slashdot.org) is included by default. If you open the Slashdot front page, it will now reload every 20 minutes, showing you the latest news.

You can also modify the frequency for refreshing in the script, by changing the numMinutes variable.

Julien Couvreur

     < Day Day Up > 


    Greasemonkey Hacks
    Greasemonkey Hacks: Tips & Tools for Remixing the Web with Firefox
    ISBN: 0596101651
    EAN: 2147483647
    Year: 2005
    Pages: 168
    Authors: Mark Pilgrim

    flylib.com © 2008-2017.
    If you may any questions please contact us: flylib@qtcs.net