Explain page redirection in ES6?

Introduced in the ES6 version of JavaScript. Page redirection is a way to send web page visitors to another URL from the current URL. We can redirect users to either the different web pages of the same website or another website or server.

In JavaScript, a window is a global object which contains the location object. We can use the different methods of the location objects for the page redirection in ES6, which is all we learn below.

Using the window.location Object’s href Attribute Value

The location object of the window global object contains the href attribute. The location object contains all the information about the location of the current webpage on which you are. The ‘href’ attribute of the location object contains the current URL.

To redirect the visitors to different URLs, we need to change the current URL in the web browser, which we can do by changing the value of the href attribute of the location object.

Syntax

Users can follow the syntax below to redirect visitors to another page by changing the href attribute’s value.

window.location = "<new_URL>";
window.location.href = "<new_URL>";

In the above syntax, if we assign a new URL value to the window.location object, by default, changes the value of the href attribute of the location object.

Using the location.assign() Method

The assign() is the method defined inside the location object. We can load the new document in the browser window using the location.assign() method and reloading the new document in the browser means redirection.

Syntax

Follow the syntax below to use the assign() method for redirection.

window.location.assign("<new_URL>");

In the above syntax, we have taken the location object as a reference to invoke the assign() method.

Parameters

  • New_URL − It is a URL on which we want to redirect the users.

Using the location.replace() Method

The replace() method of the location object works the same as the assign() method. The only difference between the replace() and assign() methods is that the replace() method replaces the current URL with a new URL in the history stack. So, It doesn’t allow the history stack to contain the information about the previous webpage, which means users can’t go back.

The assign() method adds a new entry to the history stack. So, users can go back to the previous page using the back button of the web browser.

Syntax

Users can follow the syntax below to use the replace() method for page redirection.

Window.location.replace("<redirection_URL>")

Parameters

  • Redirection_URL − The redirection URL is a new URL where we want to redirect the web page visitors.