Redirect to another web page using JavaScript
During the execution of our code, we need to redirect to another web page. There are many ways to redirect a web page to another web page in JavaScript. So today we will explain how you can easily redirect a page using JavaScript.
Redirect to another web page using JavaScript, JavaScript - Page Redirection, How to make a page redirect using JavaScript, How do I redirect with JavaScript, JavaScript URL Redirection, Using window.location to Redirect to a Different URL, Page redirect to new URL in JavaScript using window object, JavaScript Redirect, javascript redirect to relative url.
Checkout more articles on JavaScript
- Compare two dates in JavaScript
- Convert a String to a Number in JavaScript
- Replace all occurrences of a string in JavaScript
- Get Current Date & Time in JavaScript
- Round a Number to Decimal Points in JavaScript
Mostly all methods which use for web page redirection are related to window.location object, which is a property of the Window object. (For more details about Window object checkout here).
Two ways to manage the redirection of web page
1. Javascript URL redirection
Using `window.location` and `window.location.href` we can redirect to another web page. window.location is an object that holds the information about the current location of the document and href is property of window.location, window.location.href is full url of current page. Both works the same but differences in their usage.
window.location = "https://www.cluemediator.com/"
window.location.href = "https://www.cluemediator.com/";
If you want to redirect to internal website page use:
window.location.href = "/category/javascript";
2. Using location object methods
List of location object methods
- reload()
- replace()
- assign()
Let's start with another way to redirect to another web page using window location object.
Method 1: reload()
reload() method used to refresh or reload the current page.
window.location.reload();
Method 2: replace()
replace() is the method of window.location object, it will replace the current document with a new one. It rewrites the current page in history, which may affect behaviour of back button.
window.location.replace('https://www.cluemediator.com/');
Method 3: assign()
assign() method loads a new document in the browser window. This method different than replace() method because it rewrites the current page in history so when we click the back button, we go back to last visited page.
window.location.assign('https://www.cluemediator.com/');
That’s it for today.
Thank you for reading! Happy Coding!