Learn how to redirect url in javascript.
There are two different types of URL redirect possible in javascript.
1. Simulate when some one click on any anchor link.
2. Simulate an HTTP redirect.
We are going to use the window.location object to perform both type of url redirect.
Redirect like click on anchor link
We are going to use the window.location.href
to redirect to the new url. Using this method will allow to navigate back to your page by jumping backward in browser history.
window.location.href = 'https://learnersbucket.com';
Redirecting like an HTTP redirect
We can use the window.location.replace
method to redirect to the new url.
Using this method will replace the existing document with the document of the new URL. This way when you will navigate back in the browser history your existing page will not be available. Instead it will navigate to the previous page of your existing page.
window.location.replace('https://learnersbucket.com');
If you want to navigate back to the existing page in the browser history then you can use window.location.assign('https://learnersbucket.com');
There are other methods available as well which can be used for redirect.
window.location.reload("https://learnersbucket.com");
will reload the new URL on the existing page.