How to redirect to another webpage in JavaScript (JavaScript Redirect Methods)?
Introduction
If you want to redirect another webpage by using JavaScript, this article will be helpful.
If you want to redirect another webpage by using JavaScript, this article will be helpful.
JavaScript Redirect Methods
we can redirect a web page via JavaScript methods. In JavaScript, window.location or simply location object is used to get or set information about the location of the current web page (document). The following are the possible ways that can be used as a JavaScript redirect:
// Sets the new location of the current window.
window.location = "https://www.niceexample.com";
// Sets the new href (URL) for the current window.
window.location.href = "https://www.niceexample.com";
// Assigns a new URL to the current window.
window.location.assign("https://www.niceexample.com");
// Replaces the location of the current window with the new one.
window.location.replace("https://www.niceexample.com");
// Sets the location of the current window itself.
self.location = "https://www.niceexample.com";
// Sets the location of the topmost window of the current window.
top.location = "https://www.niceexample.com";
Though the above JS codes accomplish a similar job in terms of redirection, they are slightly differenc in their usages. For example, if you use top.location redirect within an iframe, it will force the main window to be redirected. Another point to keep in mind is that location.replace() replaces the current document by moving it from the history, hence making it unavailable via the Back button of the browser.
Example
Following code will redirect to google on click event
$('#id').click(function(){
window.location.href = "https://www.google.com";
});
Conclusion
I hope above descriptions are useful to redirect from JavaScript.
0 Comments