BOM Location (Window Location)

The window.location object can be used to fetch the current page address (URL) and to redirect the browser to a new page.


Window Location

The window.location object can be written without the window prefix.

Some below examples are used to get window location details:

  • window.location.href – To return the href (URL) of the current page
  • window.location.hostname – To return the domain name of the web host
  • window.location.pathname – To return the path and filename of the current page
  • window.location.protocol – To return the web protocol used (http: or https:)
  • window.location.assign() – To load a new document

Window Location Href

The window.location.href property is used to get the URL of the current page.

Example :- 
// Display the href (URL) for the current page:
document.getElementById("result").innerHTML =
"Your Page location is " + window.location.href;

Result :- 
Your Page location is http://www.lecturely.com/javascript/location.php

Window Location Hostname

The window.location.hostname property is used to get the name of the internet host (of the current page).

Example :- 
// Display the name of the your site host:
document.getElementById("result").innerHTML =
"Your Page hostname is " + window.location.hostname;
Result :- 
Your Page hostname is www.lecturely.com

Window Location Pathname

The window.location.pathname property is used to get the pathname of the current page.

Example :- 
// Display the path name of the your current url:
document.getElementById("result").innerHTML =
"Your Page path is " + window.location.pathname;
Result :- 
Your Page path is /javascript/location.php

Window Location Protocol

The window.location.protocol property is used to get the web protocol of the page.

Example :- 
// Display the web protocol:
document.getElementById("result").innerHTML =
"Your Page protocol is " + window.location.protocol;
Result :- 
Your Page protocol is http:

Window Location Port

The window.location.port property is used to get the number of the internet host port (of the current page).

Example :- 
// Display the port on which site is running:
document.getElementById("result").innerHTML =
"Your Page port is " + window.location.port;
Result :- 
Your Page port is 

Note:- Mostly browsers will not display default port numbers (80 for http and 443 for https)


Window Location Assign

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

Input:-
<!DOCTYPE html>
<html>
<body>

<h2>BOM Location</h2>

<h3>window.location object</h3>

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

<script>
function newLink() {
  window.location.assign("https://www.lecturely.com")
}
</script>

</body>
</html>

Output (Before Click):-

Output (After Click will open lecturely.com):-