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

href

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 // https://pitayan.com/posts/document-location-javascript
}

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

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

Reload page dynamically

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

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

<script>
  function reloadPage () {
    window.location.reload(true)
  }
</script>

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 google.com</button>

<script>
  function goToGoogle () {
    window.location.assign("https://google.com")
    // using replace
    // window.location.replace("https://google.com")
  }
</script>

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.

window-and-document-location

3. Location Properties

Example

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

top-page-example

Brief introduction

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

References