Javascript Get URL info with document.location

Cover image

In this article, you will learn about the usage of document location object in javascript.

1. Basic Usage


Using the location api is quite easy. What we use most frequently is perhaps the href property. This returns us the string url of the current working page.

function getURL () {
  return window.location.href //

href can also be altered in order to let browser redirect itself to a different page

window.location.href = '' // redirect to

Reload page dynamically

With reload method, we could reload the current working page on demand.

<button onclick="reloadPage()">reload page</button>

  function reloadPage () {

Redirect page dynamically

With assign or replace method, we could go to another page effortlessly. If we use replace method, we cannot use browser back button to navigate to the previous page because the history record is overrided.

<button onclick="goToGoogle()">go to</button>

  function goToGoogle () {
    // using replace
    // window.location.replace("")

2. window.location vs document.location

You may noticed that both window and document have the location property. According to W3C, these two properties are bascically the same.

They both reference to the Location Object. But in order to ensure the cross-browser compatibility, it's always preferrable to use window.location other than document.location.

If you open up Chrome browser devtools on a blank page, you can easily find out that the two properties window.location and document.location are equal.


3. Location Properties


If we take the Pitayan top page as an example, the Location Object will look like this.


Brief introduction

In a location object, the current properties / apis are as follows.