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);
}

Retrieving URL Parameter Values With Pure Javascript

Here is a short but incredibly useful piece of Javascript: it retrieves the value of a named URL parameter. For example, if the current page’s address is index.html?example=true&name=vinny this function would return vinny if passed the name name , and it would return true if passed the name example .

function getParameterByName(name) {
    var match = RegExp('[?&]' + name + '=([^&]*)').exec(window.location.search);
    return match && decodeURIComponent(match[1].replace(/\+/g, ' '));
}

A note of warning: calling this method repeatedly is inefficient, since the regular expression needs to be repeated every time.