Member-only story

Redirect, Refresh, and Access the URL of the Current Page in JavaScript

JavaScript’s location object

--

Location CheatSheet.

You can use the window.location property to access the URL of the current page .

If you want to go to a new page , either you can change the href property of history object or call assign method with new url as argument.

location.href = "new url";// or we can use location.assign("new url");

For redirecting without storing in history:

location.replace("new url"); 

For reloading the page:

window.location.reload()

Force refresh

We can pass true to force the reloaded page to come from the server (instead of the cache). Alternatively, we can use false to reload the page from the cache.

//from cache
window.location.reload();
window.location.reload(false);
// from server
window.location.reload(true);

Properties of Location Object

1. Href

Contains the entire URL of the page.

location.href; // current page url addresss

When we assign a new value to the property, it will redirect the url value set to the property.

location.href = "https://google.com"; 

Make sure to add http/https. Otherwise, it makes the request on the same page.

2. Protocol

Contains the protocol (http,https,...) of the page.

location.protocol; // https:

3. Host

Website hostname with port number.

location.host; // medium.com // with port number var anchor = document.createElement("a");
anchor.href = "https://medium.com:4097
anchor.host // "medium:4097"

4. Hostname

Website hostname.

location.host; // medium.com

5. Port

--

--

Javascript Jeep🚙💨
Javascript Jeep🚙💨

Responses (1)

Write a response