[JavaScript] window.location Example - Access Browser URL


Example of accessing browser URL (includes path, query string, etc.) via JavaScript window.location.

Demo

Source code for demo:

index.html | repository | view raw
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
<!doctype html>
<html>
<head>
  <meta charset="utf-8">
  <title>JavaScript window.location Example</title>
</head>
<body>

<div id="info"></div>

<script src="location.js"></script>
</body>
</html>
location.js | repository | view raw
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
var info = document.getElementById("info");

info.innerHTML += "href: <strong>" + window.location.href + "</strong><br>";
info.innerHTML += "host: <strong>" + window.location.host + "</strong><br>";
info.innerHTML += "hostname: <strong>" + window.location.hostname + "</strong><br>";
info.innerHTML += "pathname: <strong>" + window.location.pathname + "</strong><br>";
info.innerHTML += "protocol: <strong>" + window.location.protocol + "</strong><br>";
info.innerHTML += "origin: <strong>" + window.location.origin + "</strong><br>";
info.innerHTML += "port: <strong>" + window.location.port + "</strong><br>";
info.innerHTML += "search: <strong>" + window.location.search + "</strong><br>";
info.innerHTML += "hash: <strong>" + window.location.hash + "</strong><br>";

For GopherJS equivalent, see [1].


Tested on:

  • Ubuntu Linux 16.10
  • Chromium Version 55.0.2883.87 Built on Ubuntu , running on Ubuntu 16.10 (64-bit)

References:

[1][GopherJS] window.location - Access URL