The Window Object
Browser Location and Navigation
The location property of the Window object refers to a Location object, which represents the current URL of the document displayed in the window, and which also defines methods for making the window load a new document.
Locations
The properties of a Location object refer to the various portions of the current document’s URL.
http://www.oreilly.com:1234/catalog/search.html?q=JavaScript&m=10#results
Properties
String hash, The anchor portion of the URL, including the leading hash (#) mark—for example, “#results”.This portion of the document URL specifies the name of an anchor within the document.
String host, The hostname and port portions of the URL—for example, “http://www.oreilly.com:1234”.
String hostname, The hostname portion of a URL—for example, “http://www.oreilly.com”.
String href, The complete text of the document’s URL.
String pathname The pathname portion of a URL—for example, “/catalog/search.html”.
String port, The port portion of a URL— for example, “1234”. Note that this property is a string, not a number.
String protocol, The protocol portion of a URL, including the trailing colon—for example, “http:”.
String search, The query portion of a URL, including the leading question mark—for example, “?q=JavaScript&m=10”.
Methods
- assign(string url)
- reload()
replace(string url)
The difference between this method and assign(), is that replace() removes the URL of the current document from the document history, meaning that it is not possible to use the "back" button to navigate back to the original document.
Parsing URLs
The location property of a window is a reference to a Location object. The href property of the Location object is a string that contains the complete text of the URL. The toString() method of the Location object returns the value of the href property.
window.location.toString(); //implicitly invoke
window.loation.href;
The definition of a general-purpose urlArgs() function you can use to extract arguments from the search property of a URL.
function urlArgs() {
var args = {};
var query = location.search.substring(1);
var pairs = query.split("&");
for(var i = 0; i < pairs.length; i++) {
var pos = pairs[i].indexOf('=');
if (pos == -1) continue;
var name = pairs[i].substring(0,pos);
var value = pairs[i].substring(pos+1);
value = decodeURIComponent(value);
args[name] = value;
}
return args;
}