Categories
JavaScript

Introduction to the Location Object

Spread the love

To take us to different locations in JavaScript, we can use the location global object.

In this article, we’ll look at how to use it to get and set URLs.

Properties of the Location Object

The location object is a property of window , which is the global object.

It has a few properties.

The origin property is the URL where the link is clicked to get to the current page.

The protocol is the proto of the URL, so it’s ‘http://’ or 'https://' for most pages,

host is the hostname part of the URL, so it’s something like example.com .

hostname is the same as host if the port is 80. Otherwise, host has the port number but hostname doesn’t.

port is the port number. If it’s 80, then it’ll be an empty string.

Otherwise, it’ll be a string of the port number.

pathname is the path after the hostname.

search has the query string, so it’s something like '?page=1' .

hash has the part after the pound sign, so it’s something like '#foo' .

href hs the whole URL, so it’s something like 'http://example.com/foo?page=1' .

We can assign values to any of the properties described above.

So we can set the href property:

location.href = 'http://example.com'

Then we’ll go to 'http://example.com' .

The only property that’s read-only is the location.origin property.

Methods of the Location Object

We can call assign to assign to navigate to a given URL.

So we can call it by writing:

location.assign('http://example.com');

The replace navigates to a given URL and removes the current page from the session history.

So it does the same thing as assign but the history won’t show the current URL.

reload reloads the current page.

toString returns the URL.

Page Redirection

We can do page redirection by setting location.href or call the assign or replace methods.

For example, we can write:

location.href = 'https://example.com';

or:

location.assign('https://example.com');

or:

location.replace('https://example.com');

The first 2 will keep the current page in the session history, while replace will overwrite the session history with the new URL.

Conclusion

In the browser, we can use the location object to set the URL and get the parts of the URL.

Also, we can call its methods to call change the URL.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *