Working with the location Object
A third child of the window object is the location object. This object stores information about the current URL stored in the window. For example, the following statement loads a URL into the current window:
The href property used in this statement contains the entire URL of the window's current location. You can also access portions of the URL with various properties of the location object. To explain these properties, consider the following URL:
The following properties represent parts of the URL:
location.protocol is the protocol part of the URL (http: in the example).
location.hostname is the host name of the URL (http://www.jsworkshop.com in the example).
location.port is the port number of the URL (80 in the example).
location.pathname is the filename part of the URL (test.cgi in the example).
location.search is the query portion of the URL, if any (lines=1 in the example). Queries are used mostly by CGI scripts.
location.hash is the anchor name used in the URL, if any (#anchor in the example).
The link object, introduced earlier this hour, also includes this list of properties for accessing portions of the URL.
Although the location.href property usually contains the same URL as the document.URL property described earlier in this hour, you can't change the document.URL property. Always use location.href to load a new page.
The location object has two methods:
location.reload() reloads the current document. This is the same as the Reload button on the browser's toolbar. If you optionally include the true parameter, it will ignore the browser's cache and force a reload whether the document has changed or not.
location.replace()replaces the current location with a new one. This is similar to setting the location object's properties yourself. The difference is that the replace method does not affect the browser's history. In other words, the Back button can't be used to go to the previous location. This is useful for splash screens or temporary pages that it would be useless to return to.