Redirect to another webpage using JavaScript, JQuery & HTML


A webpage redirect will take one webpage URL and point it to another. JavaScript offers many ways to redirect the user to a different web page.
It is often required to redirect to another webpage on loading a webpage, for example, due to the contents being moved to the new webpage.
1) Using an HTML meta tag
We can redirect another URL using a meta tag in HTML:
  1. <html>
  2. <head>
  3. <meta http-equiv="refresh" content="0;URL=https://newurl.com/">
  4. </head>
  5. </html>
2) Using JavaScript
JavaScript offers many ways to redirect the user to a different web page.
Method 1:
  1. window.location.href="http://google.com";
Method 2:
The replace() method is different than the previous ways because it rewrites the current page in the history.
  1. window.location.replace("http://google.com")
Method 3:
  1. window.location.assign('https://newurl.com')
3) Using jQuery
JQuery also provide way to redirect to another page
Method 1:
  1. $(location).attr('href', 'http://google.com');
Method 2:
We can make reusable function and use it across the app.
  1. jQuery.fn.redirectTo = function(url){
  2. window.location.href = url;
  3. }
  4. jQuery(window).redirectTo("http://google.com");
As you can see, there are many methods to redirect a webpage. Hopefully, you have a better understanding of their value and why it’s something you’ll need to learn, eventually.

Post a Comment

0 Comments