YogeshChauhan.com

How to redirect or load a new document using JavaScript?

March 14, 2021

Web APIs in JavaScript are really useful. One of the interfaces available is Location interface that has several properties and methods we can take advantage of.

We can use location.replace() or location.assign() method to redirect user to a new location.

Location replace() method in JavaScript

The replace() method simply replaces the current HTML document with a new one.

Location assign() method in JavaScript

The replace() method simply loads new HTML document in the browsing window.

What’s the difference between assign() and replace() methods in JavaScript?

The replace() method removes the URL of the current document from the browser’s document history. So, that the user can not go back using the “back” button in the browser. That way you can stop users from going back to the original document.

Which one should you use between assign() and replace() methods in JavaScript?

It depends on your requirements. If you want to give your users an option to go back to the original document, use the assign() method. If not, use the replace() method.

How to use assign() method in JavaScript?

The syntax is very simple:


location.assign(URL)

where URL is a required string.

Use it like this:


location.assign("https://www.yogeshchauhan.com");

How to use replace() method in JavaScript?

Same exact way as the assign() method.

The syntax is very simple:


location.replace(URL)

where URL is a required string.

Use it like this:


location.replace("https://www.yogeshchauhan.com");

dreamhost

Most Read

#1 How to check if radio button is checked or not using JavaScript? #2 Solution to “TypeError: ‘x’ is not iterable” in Angular 9 #3 How to uninstall Cocoapods from the Mac OS? #4 How to Use SQL MAX() Function with Dates? #5 How to add Read More Read Less Button using JavaScript? #6 PHP Login System using PDO Part 1: Create User Registration Page

Recently Posted

Apr 7 Solution for “Yarn build: Failed because of a stylelint error” Apr 7 Make sure your links have descriptive text Apr 7 How to add Laravel to WordPress using Sage theme (and install Tailwind CSS)? Apr 2 How to create a sidebar using pure CSS? Apr 1 How to switch dark and light themes using pure CSS? Apr 1 How to calculate elapsed time in JavaScript?

You might also like these

Solution for “Yarn build: Failed because of a stylelint error”WordPressHow to set default timezone using PHP?PHP4 different ways to create JavaScript ObjectsJavaScriptHow to get query string values in JavaScript? (URL Manipulation using URLSearchParams)JavaScriptOverview of Drupal and how it worksDrupalCasting in PostgreSQLPostgres