04.11.2015 Views

javascript

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

Chapter 8: The Browser Object Model<br />

The location Object<br />

One of the most useful BOM objects is location , which provides information about the document that<br />

is currently loaded in the window, as well as general navigation functionality. The location object is<br />

unique in that it is a property of both window and document ; both window.location and<br />

document.location point to the same object. Not only does location know about the currently<br />

loaded document, but it also parses the URL into discrete segments that can be accessed via a series of<br />

properties. These properties are enumerated in the following table (the location prefix is assumed).<br />

Property Name Example Description<br />

hash “#contents“ The URL hash (the pound sign followed by zero<br />

or more characters), or an empty string if the URL<br />

doesn ’ t have a hash.<br />

host<br />

www.wrox.com<br />

“ www.wrox.com:80 “<br />

The name of the server and port number if<br />

present.<br />

hostname “ www.wrox.com “ The name of the server without the port number.<br />

href “ http://www.wrox.com “ The full URL of the currently loaded page. The<br />

toString() method of location returns this<br />

value.<br />

pathname “ /WileyCDA/ “ The directory and/or filename of the URL.<br />

port “ 8080 “ The port of the request if specified in the URL. If a<br />

URL does not contain a port, then this property<br />

returns an empty string.<br />

protocol “ http: “ The protocol used by the page. Typically ” http: ”<br />

or ” https: ”.<br />

search ”?q=<strong>javascript</strong>“ The query string of the URL. It returns a string<br />

beginning with a question mark.<br />

Query String Arguments<br />

Most of the information in location is easily accessible from these properties. The one part of the URL<br />

that isn ’ t provided is an easy - to - use query string. Though location.search returns everything from<br />

the question mark until the end of the URL, there is no immediate access to query - string arguments on a<br />

one - by - one basis. The following function parses the query string and returns an object with entries for<br />

each argument:<br />

function getQueryStringArgs(){<br />

//get query string without the initial ?<br />

var qs = (location.search.length > 0 ? location.search.substring(1) : “”);<br />

//object to hold data<br />

var args = {};<br />

216

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!