This quick post shows how to redirect to another webpage using JavaScript.
How to Redirect to Another Webpage Using Javascript
There are a couple of ways to redirect to another webpage with JavaScript. The most popular ones are location.href and location.replace:
Example:
// Simulate a mouse click:
window.location.href = "https://www.javaguides.net/";
// Simulate an HTTP redirect:
window.location.replace("https://www.javaguides.net/");
If you want to simulate someone clicking on a link, use location.href
If you want to simulate an HTTP redirect, use location.replace
The simplest way to test this snippet, open a console (which, in Chrome and Firefox, can be done by pressing Ctrl+Shift+I), navigate to the "console" tab, copy-and-paste each JavaScript code example from this post, and run it by pressing the Enter/Return key.
There are lots of ways of doing this.
// window.location
window.location.replace('http://www.example.com')
window.location.assign('http://www.example.com')
window.location.href = 'http://www.example.com'
document.location.href = '/path'
// window.history
window.history.back()
window.history.go(-1)
// window.navigate; ONLY for old versions of Internet Explorer
window.navigate('top.jsp')
// Probably no bueno
self.location = 'http://www.example.com';
top.location = 'http://www.example.com';
// jQuery
$(location).attr('href','http://www.example.com')
$(window).attr('location','http://www.example.com')
$(location).prop('href', 'http://www.example.com')
Comments
Post a Comment
Leave Comment