PASSWORD RESET

Your destination for complete Tech news

How to redirect to another page in Javascript?

554 0
< 1 min read

To redirect to another page in JavaScript, you can use the location object of the window object. The location object contains information about the current URL, and it provides several methods for navigating to a different URL.

The most common way to redirect to another page is to use the assign method of the location object, which loads a new page from the specified URL. Here is an example:

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

This will load the page at https://www.example.com in the current window or tab.

You can also use the replace method of the location object to replace the current page in the history with the new page. This is useful if you want to prevent the user from being able to go back to the previous page using the browser’s back button.

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

Note that the assign and replace methods will only work if the new page is on the same origin as the current page (i.e., it has the same protocol, domain, and port). If you want to redirect to a page on a different origin, you can use the window.open method to open a new window or tab with the specified URL.

window.open('https://www.example.com', '_blank');

This will open the page at https://www.example.com in a new window or tab, depending on the user’s browser settings.

It is also possible to redirect to another page using the window.location property directly. For example:

window.location = 'https://www.example.com';

This will have the same effect as using the assign method.

Leave A Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.