32

How can I redirect to another URL in a web page using JavaScript?

JohnFx
  • 33,720
  • 18
  • 99
  • 158
User
  • 901
  • 5
  • 15
  • 24
  • 1
    Not with HTML or JavaScript. You send an HTTP Location header with either a 301 or 302 status code. The specifics depend on your webserver and/or server side programming environment. – Quentin Jan 11 '12 at 17:53

7 Answers7

43
window.location.href = "URL2"

inside a JS block on the page or in an included file; that's assuming you really want to do it on the client. Usually, the server sends the redirect via a 300-series response.

Paul
  • 32,974
  • 9
  • 79
  • 112
  • With this code, when we going to webpage with `URL2` what happened? i want to redirect webpage `if user load webpage with URL1` – User Jan 11 '12 at 17:58
25

Since you tagged the question with javascript and html...

For a purely HTML solution, you can use a meta tag in the header to "refresh" the page, specifying a different URL:

<meta HTTP-EQUIV="REFRESH" content="0; url=http://www.yourdomain.com/somepage.html">

If you can/want to use JavaScript, you can set the location.href of the window:

<script type="text/javascript">
    window.location.href = "http://www.yourdomain.com/somepage.html";
</script>
David
  • 176,566
  • 33
  • 178
  • 245
11

You can redirect anything or more URL via javascript, Just simple window.location.href with if else

Use this code,

<script>
if(window.location.href == 'old_url')
{
    window.location.href="new_url";
}


//Another url redirect
if(window.location.href == 'old_url2')
{
    window.location.href="new_url2";
}
</script>

You can redirect many URL's by this procedure. Thanks.

Maniruzzaman Akash
  • 3,333
  • 1
  • 27
  • 28
4

If you want to redirect, just use window.location. Like so:

window.location = "http://www.redirectedsite.com"
3

Why javascript?

http://www.instant-web-site-tools.com/html-redirect.html

<html>
<meta http-equiv="REFRESH" content="0;url=http://www.URL2.com"> 
</html>

Unless I'm missunderstanding...

Jeff
  • 3,803
  • 11
  • 49
  • 101
1
location.href = "Pagename.html";
legoscia
  • 37,068
  • 22
  • 103
  • 148
jigish desai
  • 71
  • 1
  • 2
-1

you can also use a meta tag to redirect to another url.

<meta http-equiv="refresh" content="2;url=http://webdesign.about.com/">

http://webdesign.about.com/od/metataglibraries/a/aa080300a.htm

locrizak
  • 11,687
  • 11
  • 56
  • 80