JavaScript Window Location

Back to JS page

Table of Contents

Window Location Href

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

<!DOCTYPE html>
<html>
<body>

<h2>JavaScript Window Location</h2>
<p>From w3schools.com, Experiment by Teeratus_R</p>

<h4>Window Location Href</h4>
<p id="demo"></p>

<script>
document.getElementById("demo").innerHTML =
  "Page URL (href): " + window.location.href;
</script>

</body>
</html>

Example 1

Result View Example

Window Location Hostname

The window.location.hostname property returns the domain name of the web host:

<!DOCTYPE html>
<html>
<body>

<h2>JavaScript Window Location</h2>
<p>From w3schools.com, Experiment by Teeratus_R</p>

<h4>Window Location Hostname</h4>
<p id="demo"></p>

<script>
document.getElementById("demo").innerHTML =
  "Page hostname: " + window.location.hostname;
</script>

</body>
</html>

Example 2

Result View Example

Window Location Pathname

The window.location.pathname property returns the pathname of the current page:

<!DOCTYPE html>
<html>
<body>

<h2>JavaScript Window Location</h2>
<p>From w3schools.com, Experiment by Teeratus_R</p>

<h4>Window Location Pathname</h4>
<p id="demo"></p>

<script>
document.getElementById("demo").innerHTML =
  "Page pathname: " + window.location.pathname;
</script>

</body>
</html>

Example 3

Result View Example

Window Location Protocol

The window.location.protocol property returns the web protocol of the page (http: or https:):

<!DOCTYPE html>
<html>
<body>

<h2>JavaScript Window Location</h2>
<p>From w3schools.com, Experiment by Teeratus_R</p>

<h4>Window Location Protocol</h4>
<p id="demo"></p>

<script>
document.getElementById("demo").innerHTML =
  "Page protocol: " + window.location.protocol;
</script>

</body>
</html>

Example 4

Result View Example

Window Location Assign

The window.location.assign() method loads a new document (navigates to a new URL):

<!DOCTYPE html>
<html>
<body>

<h2>JavaScript Window Location</h2>
<p>From w3schools.com, Experiment by Teeratus_R</p>

<h4>Window Location Assign</h4>
<p id="demo"></p>

<button onclick="showAllProperties()">Show All Location Properties</button>
<p id="demo2"></p>

<script>
function showAllProperties() {
  const loc = window.location;
  document.getElementById("demo2").innerHTML =
    "href: " + loc.href + "<br>" +
    "hostname: " + loc.hostname + "<br>" +
    "pathname: " + loc.pathname + "<br>" +
    "protocol: " + loc.protocol + "<br>" +
    "port: " + loc.port + "<br>" +
    "host: " + loc.host + "<br>" +
    "origin: " + loc.origin;
}
</script>

</body>
</html>

Example 5

Result View Example

Document

Document in project

You can Download PDF file.

Reference