tags:

views:

659

answers:

4

I'm doing a peer review and I've found people using window.location.search to check what paremetes have been sent to a given (search) page.

Is it safe to do so? I was thinking that we could probably print the parameters in the HTML output inside a script block and verify the printed variables instead of querying window.location.

+3  A: 

If javascript is enabled, window.location.search is safe to use.

And just as some useless piece of further information: The property was as far as I know introduced in Netscape Navigator 2 / MS Internet Explorer 3, so I'd say it's pretty safe to use, even if it's not part of any standard (yet).

Christoph
It is part of the latest working draft for ECMAScript. You should be pretty safe using it: http://www.w3.org/TR/Window/#location
Prestaul
A: 

Safe as in 'security' or 'will this work always' ?

Even though window.location is widely it is still not part of the W3C standard. However it was added to the working draft spec in 2006: basically means a browser may or may not support it. So from a 'will this work always' you will be taking a small chance I guess.

Sesh
+1  A: 

One thing to note about this approach. window.location is set statically on page load and will not detect changes that the user has made to the address bar after that time. This should not be a concern but it is important to know.

Save the following code as an html file and fire it up in a browser:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" 
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"&gt;
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
    <head>
     <title>test</title>
    </head>
    <body>
     <a href="javascript:void(0);" 
                onclick="alert(window.location);">click me</a>
    </body>
</html>

The "click me" anchor will display the current window location onclick. However if you add anything to the address bar and click the link again it will report the same thing it did the first time.

Hopefully this is not a concern and I cannot imagine that it would affect you in any way but it is good to know.

Andrew Hare
A: 

Is it safe to do so?

Yes. Example code to get parameters as a name->value map, assuming you don't need multiple values per parameter:

function getParameters() {
    var parameters= new Object();
    var parts= window.location.search.substring(1).split('\x26');
    for (var parti= parts.length; parti-->0;) {
        var subparts= parts[parti].split(';'); // support semicolon separators as well as ampersand (see HTML 4.01 section B.2.2)
        for (var subparti= subparts.length; subparti-->0;) {
            var parparts= subparts[subparti].split('=', 2);
            if (parparts.length==2)
                parameters[decodeURIComponent(parparts[0])]= decodeURIComponent(parparts[1]);
        }
   }
   return parameters;
}
bobince