JavaScript Window Location

window.location object is used to get the address (URL) of the current page and redirect the browser to a new page.

Window Location

window.location Objects can be written without the window prefix. Some examples:

Some examples:

  • location.hostname returns the domain name of the web host
  • location.pathname returns the path and file name of the current page
  • location.port returns the port of the web host (80 or 443)
  • location.protocol returns the web protocol (http: or https :) used

Window Location Href

The location.href property returns the URL of the current page.


Returns the entire URL (of the current page):

document.getElementById("demo").innerHTML =
"Page area is " + window.location.href;

The output of the above code is:

Try it Yourself »

Window Location Hostname

The location.pathname property returns the path name of the URL.


Returns the path name of the current URL:

document.getElementById("demo").innerHTML =
"Page hostname is " + window.location.hostname;

Result is:

Try it Yourself »

Window Location Pathname

The location.assign () method loads a new document.


Load a new document:

document.getElementById("demo").innerHTML =
"Page way is " + window.location.pathname;

Result is:

Try it Yourself »

Window Location Protocol

The window.location.protocol property restores the web convention of the page.


Display the web protocol:

document.getElementById("demo").innerHTML =
"Page convention is " + window.location.protocol;

Result is:

Try it Yourself »

Window Location Assign

The window.location.assign() strategy stacks another document.


Load another document:

function newDoc() {

<input type="button" value="Load new document" onclick="newDoc()">

Try it Yourself »