Recently in one of the project I am working on required me to do a “JavaScript” based url redirect. Originally I used a PHP header based 301 redirect
1 2 3 4 |
<? header("HTTP/1.1 301 Moved Permanently"); header("Location: http://www.google.com "); ?> |
But this approach has one limitation.The limitation is that you can not send any data before the header. My client used third-party JavaScript based tracking service and he also wanted to use this service on a redirect page. ( Client demands. You deliver ). The code given below demonstrates the delayed JavaScript redirect. i.e redirect to a page after a pre specified delay in milliseconds.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
<script> window.onload = function() { Redirect(); } // Redirect after 5 seconds var count = 5; function Redirect() { if (count > 0){ document.getElementById("redirect").innerHTML = count; count = count - 1; setTimeout("Redirect()", 1000); } else { document.getElementById("redirect").innerHTML = "redirecting..."; window.open("http://www.google.com", "_self"); } } </script> |
1 2 3 4 5 6 7 8 9 10 11 12 13 |
<!doctype html> <html> <head> <meta charset="utf-8"> <script src="redirect.js"></script> <title>Redirecting.....</title> </head> <body> <div id="redirect"></div> </body> </html> |