JavaScript: Open or Redirect to Another Page / Site / Location

One of the most common uses of JavaScript is to redirect the user to or automatically open up another web page location. For example, when the user clicks a button, the JavaScript will redirect the user to the location selected in the drop down select menu. It’s just like the user has typed the web page location URL.

There are 2 ways to use JavaScript to navigate to another web page. The first is to rely on the window object:

<script type="text/javascript">
	window.location="http://www.bing.com"
</script>

The location method mimics the user behavior of typing a URL address in the address bar of the browser window. The browser then forwards to that web site, leaving the last web page in the previous entry of browsing history.

The second approach is to use the replace method of location object:

location.replace("http://www.microsoft.com");

This is trickier in that it’s not like what users would do. Instead of creating a new history entry, this method replaces the old history entry by the new one. Essentially, users cannot go back to the previous page with this approach, the previous web page is replaced by the new one: http://www.microsoft.com.

7 comments

  1. Jonay Pelluz

    This is one of things I know, but always I have to look for it in internet :-), thanks there are people out there that have posts like this with small functions :-)

    Thanks Kavoir!

  2. constance

    i tried the window location method.But i don’t know why it doesn’t redirect to the page with one-click, rather, i was asked to download the document first and it won’t lead me to the redirected page until i click on the downloaded document. Anyone who can help on this?Thanks.

    By the way, this is a newbie…

  3. Taherul Alam

    Hi there
    The function provided here (window.location=”http://www.bing.com”) may not work. You may use window.location.replace(“http://www.diit.info”) instead. Chears

  4. Abhijeet

    I tried windows.location.replace(“http://www.google.com”) but it did not work for me. Any other solutions please.
    Thank You

  5. Dinesh

    window.location=’http://www.google.com';

  6. Paul Ramnora

    I suggest you try using, instead…

    window.location.href=””

    =====

    Save the following document as being plain text ASCII/give it the name:

    js-function-test.html

    …then, left double click on it to run.

    -(NOTE: I’ve already tested the code inside of MSIE 9; and, found it works.)-

    =====

    Javascript redirect test

    Just testing…

Leave a Reply

Your email address will not be published.

*