The “location” property of the “window” object returns the location object, which contains the information about the current URL.
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);
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.
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.