The window.location object can be used to retrieve the current page URL and to navigate the browser to a different page.
The window.location object can be accessed without the window prefix.
Some examples include:
The location.href property returns the URL of the current page.
Show the URL (href) of the current page:
document.getElementById(“demo”).innerHTML = “Page location is “ + window.location.href; |
Result is:
Page location is https://www.w3schools.com/js/js_window_location.asp |
The location.hostname property returns the domain name of the host for the current page.
Show the name of the host:
document.getElementById(“demo”).innerHTML = “Page hostname is “ + window.location.hostname; |
The output is:
Page hostname is www.w3schools.com |
The location.pathname property returns the path of the current page.
Show the pathname of the current URL:
document.getElementById(“demo”).innerHTML = “Page path is “ + window.location.pathname; |
Result is:
Page path is /js/js_window_location.asp |
The location.protocol property returns the web protocol used by the current page.
Show the web protocol:
document.getElementById(“demo”).innerHTML = “Page protocol is “ + window.location.protocol; |
The result is:
Page protocol is https: |
The location.port property returns the port number of the host for the current page.
Show the host name:
document.getElementById(“demo”).innerHTML = “Port number is “ + window.location.port; |
The result is:
Port number is |
The location.assign() method loads a new document in the browser.
Load a new page:
<html> <head> <script> function newDoc() { window.location.assign(“https://www.w3schools.com”) } </script> </head> <body> <input type=”button” value=”Load new document” onclick=”newDoc()”> </body> </html> |