Using Javascript To Forward A User (And Keeping Track Of The Forward)

URL hashes (the part after the # sign) are useful for keeping track of application state. Here’s a short example of how they can be used.

The below code fragment forwards the user to a Google search for the value held in the variable q . The useful part is that this code also sets a hash to mark that the forward has taken place. This allows the page to keep track of the forwarding status, and to prevent reissuing the forward – for instance, if the user presses the back button after being forwarded.

if (location.hash != "#forwarder") {
    location.hash = "forwarder";
    var search_url = "http://www.google.com/search?q=" + escape(q);
    //Set the timeout to 10 seconds.
    setTimeout(function(){location.assign(search_url);},10000);
}

To see how this works, consider the below example. The first alert will show that there’s no hash recorded in the URL (the alert will be blank). The second line sets a hash of forwarder and the third line shows the value of the current hash (which will be the value we set on the second line). This will cause the if statement to evaluate to false, preventing the forwarding from taking place. The same process (recognizing the hash and blocking the forward) happens when the user clicks the back button on the above forwarding code.

alert(location.hash);
location.hash = "forwarder";
alert(location.hash);
if (location.hash != "#forwarder") {
    location.hash = "forwarder";
    var search_url = "http://www.google.com/search?q=" + escape(q);
    //Set the timeout to 10 seconds.
    setTimeout(function(){location.assign(search_url);},10000);
}