[JavaScript] location Object

The “location” property of the “window” object returns the location object, which contains the information about the current URL.

 

1. Properties

The “href” property returns the entire URL. But there are other properties to get the specific part of a URL.

  • href : the entire URL
  • host : the host name and port
  • hostname : the hostname
  • port : the port number
  • protocol : the protocol such as html
  • pathname : the file name part of the URL
  • search : the query part of the URL
  • hash : anchor name
console.log(window.location.href);
console.log(location.protocol + ", "
  + location.hostname + ", " + location.port);
console.log(location.pathname + ", " + location.search);

 

2. Methods

The “location” object has the following methods:

  • assign(URL) : loads a new document
  • reload(forceGet) : reloads the current page from the cache (by default) or the server (when the flag is true)
  • replace(URL) : replaces the current document with a new one

The “replace()” is similar to the “assign()” but does not affect the browser history. When the “replace()” is called, the current page is not saved in the history so you can go back to the previous page. It is useful for splash screens or temporary pages.

location.assign("http://www.google.com");

 

3. Modifying the location Object Directly

Setting the URL directly to the “location” object is a common coding practice.

window.location = "http://www.goggle.com";

When the location is modified, the document will be loaded as if window.location.assign() had been called. There might be some browser compatibility issues when you modify the location object directly. So use the “location.assign()” method.

 

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s