You can use the ‘history.back()’ method in JavaScript to navigate back to the previous page in the browser’s history. This method is a part of the ‘window.history’ object and goes back one page in the browser’s session history.

// go back to the previous page
history.back();

You could also use ‘window.history.go(-1)’ for the same result.

// go back to the previous page
window.history.go(-1);

It’s important to note that these methods will only work if the previous page was accessed via a link or the browser’s back button, and will not work if the previous page was accessed via a form submission or a browser refresh.

Another way to go back to the previous page is by using ‘window.location’ and assigning the value of ‘history.go(-1)’ to it.

window.location = history.go(-1)

You can also use ‘window.location.href = document.referrer;’ it will redirect to the previous page.

Also Read:

Categorized in: