Transfer variables from the address bar


Skip navigation.

Site search

Site navigation

Details and download

Transfer variables from the address bar into JavaScript code

This can be very useful for passing variables from one page to the next page that will be loaded. Variables can only be passed as part of a URL and cannot be retained on the user's computer except as part of a URL. It is important to note that the maximum length of a URL is 4 kB (4096 bytes). That is a limitation of the HTTP protocol, not of this script.


What it does

With server-side scripting languages [PHP, ASP, CGI (Perl and C++), JSP, ESP etc.] the variables URL-encoded into the location request are usually transferred directly into the script. This is not the case with JavaScript but the location is available, so I have written this script to locate variables within the location and transfer them directly into JavaScript.

This will work if the variables are passed in the <form method="get" ...> format. It will only work if the variables are named using characters a-z, A-Z, 0-9 and _ (not starting with 0-9).

Variables can be in any valid format:

For older browsers ...

There is a very simple version of this script that just returns the variables as part of an array. When I look back at my original version of this script, I realise that I could easily have done mine in less code using a variation on this method. At the time, I didn't think of it. The latest version does not use anything like this as to do so would in fact require more code, as mine actually creates all the variables as variables, not just entries in an array.

The simplified version does not perform any safety checks or convert + into space as it should.

var getVars = new Array();
var locvartemp = ( window.location.href.indexOf( "?" ) + 1 ) ? window.location.href.substr( window.location.href.indexOf( "?" ) + 1 ) : "";
locvartemp = locvartemp.split( "&" );
for( var x = 0; x < locvartemp.length; x++ ) {
    var lvTempVar = locvartemp[x].split( "=" );
    getVars[ unescape( lvTempVar[0] ) ] = unescape( lvTempVar[1] );

You may also be interested in my original version and my second version (which supported varName.propertyName).

How the full version works

It uses a script which is available for you to use as a JavaScript header file. It steps through the address, and if it sees a valid variable pattern, it checks if the variable (or parent variable) already exists, and if not, it creates the variable, assigning it the value specified.

To download the script(s), see the script license, and check details like browser compatibility, use the links on the navigation panel at the top of this page.

This site was created by Mark "Tarquin" Wilton-Jones.
Don't click this link unless you want to be banned from our site.