I had someone DM me this morning on Twitter and ask me what I recommended for them to use to redirect a browser using Javascript.
My gut reaction was to tell them not to do it with JavaScript, but to use Apache Redirection instead, but I went ahead and shared w/ them three ways I know to do this.
I am sure that there are more ways in javascripting to do this same thing that I don’t know about but these snippets have been in my tool box for years and they work:
Script #1 – Stealth Redirect
This allows you to redirect a page without telling your visitor, they probably won’t even notice it happen.
1: <html>
2: <script>
3: location = "http://cottonrohrscheib.com";4: </script>
5: </html>
Script #2 – Alert Redirect
If you want visitors to know that the page has been moved you could use this script. It uses a JavaScript alert, to tell your visitor that the page has been moved, then when they click OK, their browser is redirected.
1: <html>
2: <script>
3: alert("This page has been moved to a new location... click OK to be redirected?");4: location = "http://www.cottonrohrscheib.com";5: </script>
6: </html>
Script #3 – Confirm Redirect
If you want to give your visitors more control, you can use a confirm dialog. This script gives visitors the option to either be redirected to the new location or go back to the previous page.
1: <html>
2: <script>
3: if(confirm("This page has been moved to a new location... would you like to be redirected?"))4: {
5: location = "http://www.cottonrohrscheib.com";6: }
7: else8: {
9: history.back();
10: }
11: </script>
12: </html>
As I mentioned, these all work, just pick out which one best suits your particular situation. Be sure to change out the URL from mine to yours and you should be good to go.
Please Drop Your Questions or Comments