Curriculum
Course: JavaScript Basic
Login

Curriculum

JavaScript Basic

JSHome

0/216
Text lesson

JS location

The window.location object can be used to retrieve the current page URL and to navigate the browser to a different page.

Window Location

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

Some examples include:

  • location.href returns the URL of the current page.
  • location.hostname returns the domain name of the web host.
  • location.pathname returns the path and filename of the current page.
  • location.protocol returns the web protocol used (e.g., http: or https:).
  • location.assign() loads a new document.

Window Location Href

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

Example

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

Window Location Hostname

The location.hostname property returns the domain name of the host for the current page.

Example

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

Window Location Pathname

The location.pathname property returns the path of the current page.

Example

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

Window Location Protocol

The location.protocol property returns the web protocol used by the current page.

Example

Show the web protocol:

document.getElementById(“demo”).innerHTML =
“Page protocol is “ + window.location.protocol;

The result is:

Page protocol is https:

Window Location Port

The location.port property returns the port number of the host for the current page.

Example

Show the host name:

document.getElementById(“demo”).innerHTML =
“Port number is “ + window.location.port;

The result is:

Port number is

Window Location Assign

The location.assign() method loads a new document in the browser.

Example

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>