By venkatachalam


2009-02-02 12:54:16 8 Comments

How can I redirect the user from one page to another using jQuery or pure JavaScript?

30 comments

@Mark Pieszak - Trilon.io 2012-07-27 14:41:13

Standard "vanilla" JavaScript way to redirect a page

window.location.href = 'newPage.html';

Or more simply: (since window is Global)

location.href = 'newPage.html';

If you are here because you are losing HTTP_REFERER when redirecting, keep reading:

(Otherwise ignore this last part)


The following section is for those using HTTP_REFERER as one of many secure measures (although it isn't a great protective measure). If you're using Internet Explorer 8 or lower, these variables get lost when using any form of JavaScript page redirection (location.href, etc.).

Below we are going to implement an alternative for IE8 & lower so that we don't lose HTTP_REFERER. Otherwise you can almost always simply use window.location.href.

Testing against HTTP_REFERER (URL pasting, session, etc.) can be helpful in telling whether a request is legitimate. (Note: there are also ways to work-around / spoof these referrers, as noted by droop's link in the comments)


Simple cross-browser testing solution (fallback to window.location.href for Internet Explorer 9+ and all other browsers)

Usage: redirect('anotherpage.aspx');

function redirect (url) {
    var ua        = navigator.userAgent.toLowerCase(),
        isIE      = ua.indexOf('msie') !== -1,
        version   = parseInt(ua.substr(4, 2), 10);

    // Internet Explorer 8 and lower
    if (isIE && version < 9) {
        var link = document.createElement('a');
        link.href = url;
        document.body.appendChild(link);
        link.click();
    }

    // All other browsers can use the standard window.location.href (they don't lose HTTP_REFERER like Internet Explorer 8 & lower does)
    else { 
        window.location.href = url; 
    }
}

@droope 2013-01-29 23:41:11

Foot note: checking for referrer as a security measure is a lousy solution. duckduckgo.com/?q=referrer+spoofing

@Andrew Fox 2015-08-21 04:31:05

If you have an HTTP GET session ID in the referrer URL it can be used to check that against the session for validity.

@Buzinas 2015-09-30 18:35:27

@mcpDESIGNS are you sure that you've tried to use location.assign? I use in my app with IE8, and I don't lose the HTTP_REFERER header.

@Mark Pieszak - Trilon.io 2018-02-26 00:41:47

At least back in 2012 it wasn't working, maybe later patches of IE8 fixed it - that's good to hear though!

@Dov Miller 2019-01-09 10:09:54

Your mention of HTTP_REFERER helped me understand the problem I'm having with window.open and I found a solution here: stackoverflow.com/questions/7580613/…. By the way I'm having the problem in IE11!

@Mayur 2019-03-07 07:16:40

Here I mentions some other use of window.location. window.location.href returns the href (URL) of the current page window.location.hostname returns the domain name of the web host window.location.pathname returns the path and filename of the current page window.location.protocol returns the web protocol used (http: or https:) window.location.assign loads a new document

@Vinay Sharma 2013-12-10 10:09:27

You can use it like in the following code where getRequestToForwardPage is the request mapping (URL). You can also use your URL.

function savePopUp(){
    $.blockUI();
    $.ajax({
        url:"GuestHouseProcessor?roomType="+$("#roomType").val(),
        data: $("#popForm").serialize(),
        dataType: "json",
        error: (function() {
            alert("Server Error");
            $.unblockUI();
    }),
    success: function(map) {
        $("#layer1").hide();
        $.unblockUI();
        window.location = "getRequestToForwardPage";
    }
});

This is for the same context of the application.

If you want to use only jquery specific code then following code may help:

 $(location).attr('href',"http://www.google.com");
 $jq(window).attr("location","http://www.google.com");
 $(location).prop('href',"http://www.google.com"); 

@Andrei Todorut 2017-12-22 21:00:58

Using location.replace() will redirect you but without saving the history of the previous page. This better to use when a form is submitted. But when you want to keep your history you have to use location.href=//path

Examples:

// form with steps
document.getElementById('#next').onclick = function() {
   window.location.href='/step2' // iteration of steps;
}

// go to next step
document.getElementById('#back').onclick = function() {
   window.history.back();
}

// finish 
document.getElementById('#finish').onclick = function() {
   window.location.href = '/success';
}

// on success page
window.onload = function() {
    setTimeout(function() {
       window.location.replace('/home'); // i can't go back to success page by pressing the back button
    },3000);
}

@Patrick W. McMahon 2014-08-27 21:50:35

Before I start, jQuery is a JavaScript library used for DOM manipulation. So you should not be using jQuery for a page redirect.

A quote from Jquery.com:

While jQuery might run without major issues in older browser versions, we do not actively test jQuery in them and generally do not fix bugs that may appear in them.

It was found here: https://jquery.com/browser-support/

So jQuery is not an end-all and be-all solution for backwards compatibility.

The following solution using raw JavaScript works in all browsers and have been standard for a long time so you don't need any libraries for cross browser support.

This page will redirect to Google after 3000 milliseconds

<!DOCTYPE html>
<html>
    <head>
        <title>example</title>
    </head>
    <body>
        <p>You will be redirected to google shortly.</p>
        <script>
            setTimeout(function(){
                window.location.href="http://www.google.com"; // The URL that will be redirected too.
            }, 3000); // The bigger the number the longer the delay.
        </script>
    </body>
</html>

Different options are as follows:

window.location.href="url"; // Simulates normal navigation to a new page
window.location.replace("url"); // Removes current URL from history and replaces it with a new URL
window.location.assign("url"); // Adds new URL to the history stack and redirects to the new URL

window.history.back(); // Simulates a back button click
window.history.go(-1); // Simulates a back button click
window.history.back(-1); // Simulates a back button click
window.navigate("page.html"); // Same as window.location="url"

When using replace, the back button will not go back to the redirect page, as if it was never in the history. If you want the user to be able to go back to the redirect page then use window.location.href or window.location.assign. If you do use an option that lets the user go back to the redirect page, remember that when you enter the redirect page it will redirect you back. So put that into consideration when picking an option for your redirect. Under conditions where the page is only redirecting when an action is done by the user then having the page in the back button history will be okay. But if the page auto redirects then you should use replace so that the user can use the back button without getting forced back to the page the redirect sends.

You can also use meta data to run a page redirect as followed.

META Refresh

<meta http-equiv="refresh" content="0;url=http://evil.com/" />

META Location

<meta http-equiv="location" content="URL=http://evil.com" />

BASE Hijacking

<base href="http://evil.com/" />

Many more methods to redirect your unsuspecting client to a page they may not wish to go can be found on this page (not one of them is reliant on jQuery):

https://code.google.com/p/html5security/wiki/RedirectionMethods

I would also like to point out, people don't like to be randomly redirected. Only redirect people when absolutely needed. If you start redirecting people randomly they will never go to your site again.

The next paragraph is hypothetical:

You also may get reported as a malicious site. If that happens then when people click on a link to your site the users browser may warn them that your site is malicious. What may also happen is search engines may start dropping your rating if people are reporting a bad experience on your site.

Please review Google Webmaster Guidelines about redirects: https://support.google.com/webmasters/answer/2721217?hl=en&ref_topic=6001971

Here is a fun little page that kicks you out of the page.

<!DOCTYPE html>
<html>
    <head>
        <title>Go Away</title>
    </head>
    <body>
        <h1>Go Away</h1>
        <script>
            setTimeout(function(){
                window.history.back();
            }, 3000);
        </script>
    </body>
</html>

If you combine the two page examples together you would have an infant loop of rerouting that will guarantee that your user will never want to use your site ever again.

@Patrick W. McMahon 2015-06-27 12:16:27

I address his request for jQuery by saying it's not needed. JQuery has a lot of great useful shortcuts for JavaScript but there is no need for any shortcuts for redirects. JQuery is just JavaScript. Nothing more. The normal way to call a redirect will work with his functions using jQuery.

@Epirocks 2015-06-30 22:17:17

Patrick, by your own logic there is no need for JQuery in all situations. The whole point is convenience, and the question asked for it. The best tool I'd say is the JQuery version because it will probably abstract away browser specifics for the future. So your argument is still null and void. The question asked for JQuery.

@Epirocks 2015-07-02 22:19:42

You may be right about that currently, however you are not able to see the future and cannot at this time predict how future proof it is. And the fact remains the question asked for JQuery!

@Epirocks 2015-07-05 18:45:26

"Yeah JavaScript could change and if it changes then jQuery then needs to change as jQuery is JavaScript. – Patrick W. McMahon yesterday" Thankyou, I rest my case.

@Patrick W. McMahon 2015-07-05 18:50:59

You have no case. JQuery has a higher chance to change then JavaScript. New version of JQuery get realest all the time and old jQuery becomes obsolete and them makes problems will code reliant on a set version of JQuery.

@Patrick W. McMahon 2015-07-05 19:12:53

JQuery frequently breaks from version to version. Many drupal and wordpress plugins often only work with set jQuery version's and will not work with newer ones.

@Patrick W. McMahon 2015-07-05 19:14:27

Multiple jQuery version's have changed everything about jQuery and was not backwards compatible

@Epirocks 2015-07-05 19:33:38

Hence keeping up-to-date with the latest one. 1.9 was a big one, the breaking changes are documented. Version 2.0 don't like IE 8 and lower, and quite rightly so. So it depends what you mean by broken. Changes are to get JQuery onto a better path and better able to handle changes.

@Patrick W. McMahon 2015-07-05 19:37:52

JQuery has changed and has had version problems so based on it's past you can't say it will not happen again.

@Newse 2014-02-16 14:42:55

Should just be able to set using window.location.

Example:

window.location = "https://stackoverflow.com/";

Here is a past post on the subject: How do I redirect to another webpage?

@Jaider 2016-11-11 20:25:22

It maybe works, but I am not sure if this the right way to do it. I'm not see documentation that support this. It could leads programmers to a bad programming practices.

@Boris Guéry 2009-10-28 16:35:36

WARNING: This answer has merely been provided as a possible solution; it is obviously not the best solution, as it requires jQuery. Instead, prefer the pure JavaScript solution.

$(location).attr('href', 'http://stackoverflow.com')

@barrymac 2012-01-12 12:00:40

This is that literal answer to the question. If you are already using Jquery and therefore have it already loaded then it will be more bandwidth efficient and of course clearer to use the shortcut

@Chris 2012-02-29 16:03:25

More importantly, is there a way to do this with jQuery that is absracted? This is just a wrapper for window.location.href = url; But if jQuery had some function that, if window.location.href = url; wasn't going to work in the current environment (browser, OS, etc.) jQuery core could compensate?

@Tim Down 2012-10-03 10:32:36

Forcing jQuery into the equation in this way is just ridiculous and pointless, especially since window.location is not an element and therefore does not have attributes.

@Mad Scientist 2013-02-18 12:08:28

I think window.location does not work on some IE versions.The point of jQuery is not just easing front end scripting but making it cross browser too.

@ThiefMaster 2013-07-03 11:23:52

I somehow doubt this still works with recent jQuery versions where .attr() actually sets attributes (i.e. .setAttribute())

@JCM 2014-01-23 15:48:46

@deltaray This is not another way to redirect, like said above, it's a meaningless wrapper around the location object, which, is not even an element! This reminds me of i.stack.imgur.com/ssRUr.gif

@vp_arth 2014-04-04 20:06:58

also $(location)[0].href = url; and even $, location.href = url; I prefer second jQuery solution

@Gustavo Rodrigues 2014-08-11 20:06:16

I know it is an old question, there is a curiosity: some XSS filters don't allow things like <script>location="http://example.com;</script>" and will block it, but if you use jQuery they will not block it.

@Ben 2014-10-12 01:05:18

No need for the warning, the OP asked for a JQ answer, and so he/she shall receive.

@Henry Heleine 2014-12-09 21:50:28

jQuery will at least take care of any cross-browser compatibility issues with the different JavaScript APIs.

@Patrick W. McMahon 2015-11-18 21:54:00

Why on earth would you ever do this. JQuery is meant as a DOM manipulation library. Not for this. This solution is a bad solution. The OP asked for JQuery and the answer should be to tell the OP that JQuery is not needed and not used for this. The right tool for the right job. JQuery is great for DOM but should not be forced to do things its not meant to do.

@Nick Coad 2016-01-13 05:55:38

This is a really, really bad answer and I'm stunned by the number of votes it has received. The attr() method is used for setting attribute values on DOM objects. Using it for this is counter to the intention of the method and thus you cannot possibly guarantee that this method will work in the future.

@rvighne 2016-07-12 22:40:17

As the location object is supported in literally every browser in use today, there's no way using jQuery will make this code more "cross-browser"

@xDaizu 2016-08-26 09:02:35

People, maybe jQuery it is not required to redirect. Maybe jQuery is NOT the Right Way™ to redirect. Maybe OP didn't really mean jQuery, just Javascript. But the fact is you can redirect with jQuery and if, for any reason, you want to do it, this is the (kinda hacky) way to do it. I think that this answer, warning included is the best way to answer this question as it is stated.

@jave.web 2016-12-12 12:28:37

IF you use jQuery for this, use .prop() , because of what @Tim Down said :-)

@Pablo Palacios 2017-05-04 17:15:20

Actually the question is how to makeit with JQUERY, not how to do it on plain vanilla javascript. This should be the answer.

@keji 2017-10-09 13:41:34

If you know exactly what jQuery does you know it literally is doing a million operations just to set "location.href". This is not browser cross-compatible, it does not save bandwidth. But if you want a run through of what happens: 1) $() is a function that wraps, arrays and objects, and things in the DOM (what it's meant for), In this case 'location' is a object. "attr" sets a certain key on that object, after going another million operations. None of those operations include browser checks for this case because no such thing exists. It's just a waste to set an object's property.

@Ryan McGeary 2009-02-03 04:24:09

One does not simply redirect using jQuery

jQuery is not necessary, and window.location.replace(...) will best simulate an HTTP redirect.

window.location.replace(...) is better than using window.location.href, because replace() does not keep the originating page in the session history, meaning the user won't get stuck in a never-ending back-button fiasco.

If you want to simulate someone clicking on a link, use location.href

If you want to simulate an HTTP redirect, use location.replace

For example:

// similar behavior as an HTTP redirect
window.location.replace("http://stackoverflow.com");

// similar behavior as clicking on a link
window.location.href = "http://stackoverflow.com";

@Abhi 2012-04-19 11:52:02

in case of submit button add return false ; also inside your function

@Hoppe 2013-01-24 00:51:34

The question is about javascript specifically, but it may be worth noting that a meta refresh can be used as a fail back in case the user has javascript disabled

@Jeff Noel 2013-06-07 13:28:29

@NicolòMartini If(IE) document.write("");

@Stano 2013-06-14 10:28:57

@Erik Reppen 2013-06-16 02:55:14

Why do we never get explicit with document but it's always window.location or window.open? Properties of window are global.

@null 2013-08-11 10:02:23

this didn't work for my scenario but this did : stackoverflow.com/questions/12591953/…

@user1529956 2013-12-06 17:15:29

What code can I use so the redirect works in production and development? Because the domain differs of course

@Michael Papworth 2014-01-13 10:38:43

@NicolòMartini this is how I work around the referrer issue, also it gives me a nice tidy way to abstract site navigation logic away github.com/michaelpapworth/jQuery.navigate

@Noz 2015-01-28 22:34:13

If you're already using jQuery, just use $(location).attr('href',url);. window.location.href seems to have inconstant behavior in some browsers, in fact, it flat out doesn't work in my version of Firefox. I've heard tell of setting window.location directly not working in versions of IE.

@victor sosa 2015-03-31 20:45:07

There is an issue with this code, because the same code doesn't work when you go back using the back button. It just doesn't work anymore.

@Jacques Marais 2015-09-24 15:56:55

@RyanMcGeary When using window.location.replace(), can I only add the directory, or must I include the host?

@Ryan McGeary 2015-09-24 20:22:33

@JacquesMarais Yes, relative and absolute paths should both work. Just like the href attribute in an anchor tag <a>.

@MadMaardigan 2017-03-23 15:35:45

"is better" should be removed. As stated later in the answer, the best solution is situational. OP does not ask "how can I emulate an HTTP redirect with Javascript..."

@Black 2017-09-14 15:03:58

Does not work if a link begins with www. It does only work with http or https. But how can we make sure that the website even supports https?!

@Ketan Savaliya 2018-04-09 07:57:32

See demo @ jquerypot.com/…

@Black 2018-04-20 07:46:44

Thats incorrect, you CAN redirect. Look here: stackoverflow.com/a/19036954/4684797

@ytpillai 2018-05-15 21:12:59

Why not just use a Location header?

@Bob Ray 2018-06-05 05:23:59

Excellent! Using replace is the only way around the "Headers already sent" error. It solves all kinds of problems with output buffering and timely progress reporting. I used it inside a recursive AJAX loop to report the progress, then forward to another page when finished.

@user7637745 2018-06-15 08:25:38

Although I've used and still use jQuery for many projects, whenever I had to redirect the page, I've always used window.location.*. In my opinion, when we us JavaScript, we should use the built-in methods, if they are available and properly implemented.

@Lamy 2018-11-23 16:23:52

@Hoppe, who disables JavaScript nowadays?

@Hoppe 2018-11-24 04:24:15

@Lamy, I guess I should have phrased it differently. Ie, technically you don't even need JavaScript to redirect. I do also wonder if there are any accessibility programs that disable JS,

@tecnocrata 2018-12-12 18:01:21

@Mayur 2019-03-07 07:15:10

Here I mentions some other use of window.location. window.location.href returns the href (URL) of the current page window.location.hostname returns the domain name of the web host window.location.pathname returns the path and filename of the current page window.location.protocol returns the web protocol used (http: or https:) window.location.assign loads a new document

@Umair Anwar 2019-06-23 12:16:17

window.location.replace(url) replaces only last entry in the back button history. For example; 1. If you open stackoverflow.com and then execute window.location.replace("anynewdomain1.com"), the back button history will be empty. So, back button will be showing as disabled as its history is empty. 2. If you open Site A and then redirect to stackoverflow.com using window.location.href, then execute window.location.replace("anynewdomain1.com"), the back button history will take you back to SiteA instead of stackoverflow.com as its entry is replaced.

@JL2210 2019-07-11 14:20:09

"won't get stuck in a never-ending back-button fiasco" I've been on many sites where this is just an absolute nightmare,

@Ashish Ratan 2014-01-27 10:11:14

You need to put this line in your code:

$(location).attr("href","http://stackoverflow.com");

If you don't have jQuery, go with JavaScript:

window.location.replace("http://stackoverflow.com");
window.location.href("http://stackoverflow.com");

@ruX 2016-09-22 18:12:41

what the point of wrapping everything in jquery?

@Asif J 2018-03-30 11:43:31

Javascript is very extensive. If you want to jump to another page you have three options.

 window.location.href='otherpage.com';
 window.location.assign('otherpage.com');
 //and...

 window.location.replace('otherpage.com');

As you wants to move to other page you can use any from these if this is your requirment However all three options are limited to diffrent situations. Chose wisely according to your requirment.

if you are intrested in more knowledge about the concept. You can go through further.

window.location.href; returns the href (URL) of the current page
window.location.hostname; returns the domain name of the web host
window.location.pathname; returns the path and filename of the current page
window.location.protocol; returns the web protocol used (http: or https:)
window.location.assign; loads a new document

@Alireza 2017-02-26 13:36:49

Basically jQuery is just a JavaScript framework and for doing some of the things like redirection in this case, you can just use pure JavaScript, so in that case you have 3 options using vanilla JavaScript:

1) Using location replace, this will replace the current history of the page, means that it is not possible to use the back button to go back to the original page.

window.location.replace("http://stackoverflow.com");

2) Using location assign, this will keep the history for you and with using back button, you can go back to the original page:

window.location.assign("http://stackoverflow.com");

3) I recommend using one of those previous ways, but this could be the third option using pure JavaScript:

window.location.href="http://stackoverflow.com";

You can also write a function in jQuery to handle it, but not recommended as it's only one line pure JavaScript function, also you can use all of above functions without window if you are already in the window scope, for example window.location.replace("http://stackoverflow.com"); could be location.replace("http://stackoverflow.com");

Also I show them all on the image below:

location.replace location.assign

@marsze 2018-08-23 07:57:15

I recommend using assign() over href= too as the latter did not work properly for me in some cases.

@Govind Singh 2014-01-28 04:28:26

There are lots of ways of doing this.

// window.location
window.location.replace('http://www.example.com')
window.location.assign('http://www.example.com')
window.location.href = 'http://www.example.com'
document.location.href = '/path'

// window.history
window.history.back()
window.history.go(-1)

// window.navigate; ONLY for old versions of Internet Explorer
window.navigate('top.jsp')


// Probably no bueno
self.location = 'http://www.example.com';
top.location = 'http://www.example.com';

// jQuery
$(location).attr('href','http://www.example.com')
$(window).attr('location','http://www.example.com')
$(location).prop('href', 'http://www.example.com')

@Rob W 2014-11-26 18:19:10

window.navigate is old-IE-only (Firefox/Chrome do not support this). If you want to enumerate all options, don't forget about document.location.

@Léo Lam 2015-07-17 07:13:15

This does not explain anything at all. What is someone supposed to pick? Pick one randomly from the list? Also, what does this add to the existing answers?

@Ali Humayun 2015-07-30 20:22:46

document.location = document.referrer; Please add it in list also. This does not work like History.back rather makes the page Refresh again.

@Rivalus 2016-06-19 20:41:21

.attr() will not work on jQuery 3.0.0. use .val() instead.

@I am the Most Stupid Person 2017-09-18 10:43:02

@LéoLam That's why there is a search engine called Google. :-) You can search each each one on Google and find the difference. You don't want to pick one randomly.

@Léo Lam 2017-09-18 10:44:23

@IamtheMostStupidPerson exactly my point. The answer is useless.

@John Balvin Arias 2018-05-25 10:12:24

@SergeDirect 2014-12-26 19:08:21

*****THE ORIGINAL QUESTION WAS - "HOW TO REDIRECT USING JQUERY", HENCE THE ANSWER IMPLEMENTS JQUERY >> COMPLIMENTARY USAGE CASE*****

To just redirect to a page with JavaScript:

  window.location.href = "/contact/";

Or if you need a delay:

setTimeout(function () {
  window.location.href = "/contact/";
}, 2000);   // Time in milliseconds

jQuery allows you to select elements from a web page with ease. You can find anything you want on a page and then use jQuery to add special effects, react to user actions, or show and hide content inside or outside the element you have selected. All these tasks start with knowing how to select an element or an event.

     $('a,img').on('click',function(e){
         e.preventDefault();
         $(this).animate({
             opacity: 0 //Put some CSS animation here
         }, 500);
         setTimeout(function(){
           // OK, finished jQuery staff, let's go redirect
           window.location.href = "/contact/";
         },500);
     });

Imagine someone wrote a script/plugin that is 10000 lines of code?! Well, with jQuery you can connect to this code with just a line or two.

@cnexans 2018-10-12 19:55:31

It is preferable not to write in caps, although good answer

@Alessandro Foolish Ciak DAnton 2018-02-17 20:31:42

If you prefer to use pure javascript I realized that using of document.location.href = "https://example.com" or window.location.href = "https://example.com" causes compatibility issues in Firefox. Instead try to use:

location.href = "https://example.com";
location.replace("http://example.com");

In my case has solved the problem. Good luck!

@wild coder 2018-02-14 10:35:50

You can write the Url.Action for the Button click event in the script section as follows.

function onclick() {
        location.href = '@Url.Action("Index","Home")';
    }

@Mehmet Taha Meral 2019-01-07 15:38:54

Who said that it's ASP.Net MVC project? :)

@Inconnu 2016-12-13 10:43:32

In jQuery, use $(location).attr('href', url):

$(document).ready(function(){
    var url = "https://www.youtube.com/watch?v=JwMKRevYa_M";
    $(location).attr('href', url); // Using this
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

In raw JavaScript, there are a number of ways to achieve that:

window.location.href="https://www.youtube.com/watch?v=JwMKRevYa_M";

- sets href property explicitly.

window.location = "http://www.GameOfThrones.com";

- does it implicitly Since window.location returns an object, which by default sets its .href property.

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

- replaces the location of the current window with the new one.

self.location = "http://www.somewebsite.com";

- sets the location of the current window itself.

Here is an example of JavaScript redirecting after a certain time (3 seconds):

<script>
    setTimeout(function() {
        window.location.href = "https://www.youtube.com/";
    }, 3000);
</script>

@1j01 2017-03-09 17:34:59

Even if you're "in jQuery" (more accurately, you have jQuery available), you shouldn't use it for this purpose.

@Kalpesh Panchal 2017-02-23 23:01:28

Using JavaScript:

Method 1:

window.location.href="http://google.com";

Method 2:

window.location.replace("http://google.com");

Using jQuery:

Method 1: $(location)

$(location).attr('href', 'http://google.com');

Method 2: Reusable Function

jQuery.fn.redirectTo = function(url){
    window.location.href = url;
}

jQuery(window).redirectTo("http://google.com");

@CPHPython 2018-04-16 09:33:01

Why so many snippets? You cannot see the redirection happening, you know...? The last couple ones show an error because you did not include jQuery.

@Maniruzzaman Akash 2017-05-26 19:23:55

I just add another way:

To redirect for any specific page/links of your site to another page, just add this line of 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>

For a real life example,

<script>
    if(window.location.href == 'https://old-site.com')
    {
        window.location.href="https://new-site.com";
    }

    // Another URL redirect
    if(window.location.href == 'https://old-site.com/simple-post.html')
    {
        window.location.href="https://new-site.com/simple-post.html";
    }
</script>

By using this simple code, you can redirect full site or any single page.

@Mohideen bin Mohammed 2017-06-27 09:36:11

  1. location.assign():

    To assign a route path by passing a path into it.. Assign will give you a history even after the path was assigned.

    Usage Method: value should be passed into it.

    For example: location.assign("http://google.com")

    Enter image description here

  2. location.href

    Can define give a path into it... And it will redirect into a given path once it setup, and it will keep history...

    Usage Method: value should be assign into it.

    For example: location.href = "http://google.com"

  3. location.replace():

    It will help to replace a path if you don't want to keep history. It won't give you a history once you replace its path.

    Usage Method: value should be pass into it.

    For example: location.replace("http://google.com")

    Enter image description here


assign() and href are similar, and both can hold history. assign will work by passing a value and href works by assigning.

You can achieve it using JavaScript itself without using jQuery by assigning,

window.location = "http://google.com"
location.href = "http://google.com"

You can achieve similar thing using jQuery like below. It will do exactly the same like above,

$(window).attr('location', "http://www.google.com");
$(location).attr('href', "http://www.google.com");

You can easily understand the difference between both...

Here is the Location object,

Location API from chrome

@HD.. 2017-08-28 06:01:38

Single Page Application, within the same application route

window.location.pathname = '/stack';

JavaScript:

location.href = "http://stack.com";
window.location = "http://stack.com";

jQuery:

$(location).attr('href', "http://www.stack.com");
$(window).attr('location', "http://www.stack.com");

Angular 4

import { Router } from '@angular/router';
export class NavtabComponent{
    constructor(private router: Router) {
    }
    this.router.navigate(['bookings/taxi']);
}

@Omkaar.K 2017-12-07 22:08:15

In my work experience, JavaScript is much better to redirect.

It depends on how you want to change the location. If you want to log your website in users history, use window.location.href='ur website';. Otherwise to do it without logging in history, use window.location.replace("your website");.

@Patartics Milán 2013-04-25 10:12:24

I also think that location.replace(URL) is the best way, but if you want to notify the search engines about your redirection (they don't analyze JavaScript code to see the redirection) you should add the rel="canonical" meta tag to your website.

Adding a noscript section with a HTML refresh meta tag in it, is also a good solution. I suggest you to use this JavaScript redirection tool to create redirections. It also has Internet Explorer support to pass the HTTP referrer.

Sample code without delay looks like this:

<!-- Place this snippet right after opening the head tag to make it work properly -->

<!-- This code is licensed under GNU GPL v3 -->
<!-- You are allowed to freely copy, distribute and use this code, but removing author credit is strictly prohibited -->
<!-- Generated by http://insider.zone/tools/client-side-url-redirect-generator/ -->

<!-- REDIRECTING STARTS -->
<link rel="canonical" href="https://yourdomain.com/"/>
<noscript>
    <meta http-equiv="refresh" content="0;URL=https://yourdomain.com/">
</noscript>
<!--[if lt IE 9]><script type="text/javascript">var IE_fix=true;</script><![endif]-->
<script type="text/javascript">
    var url = "https://yourdomain.com/";
    if(typeof IE_fix != "undefined") // IE8 and lower fix to pass the http referer
    {
        document.write("redirecting..."); // Don't remove this line or appendChild() will fail because it is called before document.onload to make the redirect as fast as possible. Nobody will see this text, it is only a tech fix.
        var referLink = document.createElement("a");
        referLink.href = url;
        document.body.appendChild(referLink);
        referLink.click();
    }
    else { window.location.replace(url); } // All other browsers
</script>
<!-- Credit goes to http://insider.zone/ -->
<!-- REDIRECTING ENDS -->

@Nikhil Agrawal 2013-12-23 13:35:15

JavaScript provides you many methods to retrieve and change the current URL which is displayed in browser's address bar. All these methods uses the Location object, which is a property of the Window object. You can create a new Location object that has the current URL as follows..

var currentLocation = window.location;

Basic Structure of a URL

<protocol>//<hostname>:<port>/<pathname><search><hash>

enter image description here

  1. Protocol -- Specifies the protocol name be used to access the resource on the Internet. (HTTP (without SSL) or HTTPS (with SSL))

  2. hostname -- Host name specifies the host that owns the resource. For example, www.stackoverflow.com. A server provides services using the name of the host.

  3. port -- A port number used to recognize a specific process to which an Internet or other network message is to be forwarded when it arrives at a server.

  4. pathname -- The path gives info about the specific resource within the host that the Web client wants to access. For example, stackoverflow.com/index.html.

  5. query -- A query string follows the path component, and provides a string of information that the resource can utilize for some purpose (for example, as parameters for a search or as data to be processed).

  6. hash -- The anchor portion of a URL, includes the hash sign (#).

With these Location object properties you can access all of these URL components

  1. hash -Sets or returns the anchor portion of a URL.
  2. host -Sets or returns the hostname and port of a URL.
  3. hostname -Sets or returns the hostname of a URL.
  4. href -Sets or returns the entire URL.
  5. pathname -Sets or returns the path name of a URL.
  6. port -Sets or returns the port number the server uses for a URL.
  7. protocol -Sets or returns the protocol of a URL.
  8. search -Sets or returns the query portion of a URL

Now If you want to change a page or redirect the user to some other page you can use the href property of the Location object like this

You can use the href property of the Location object.

window.location.href = "http://www.stackoverflow.com";

Location Object also have these three methods

  1. assign() -- Loads a new document.
  2. reload() -- Reloads the current document.
  3. replace() -- Replaces the current document with a new one

You can use assign() and replace methods also to redirect to other pages like these

location.assign("http://www.stackoverflow.com");

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

How assign() and replace() differs -- The difference between replace() method and assign() method(), is that replace() removes the URL of the current document from the document history, means it is not possible to use the "back" button to navigate back to the original document. So Use the assign() method if you want to load a new document, andwant to give the option to navigate back to the original document.

You can change the location object href property using jQuery also like this

$(location).attr('href',url);

And hence you can redirect the user to some other url.

@Divyesh Kanzariya 2016-03-03 10:50:15

jQuery code to redirect a page or URL

First Way

Here is the jQuery code for redirecting a page. Since, I have put this code on the $(document).ready() function, it will execute as soon as the page is loaded.

var url = "http://stackoverflow.com";
$(location).attr('href',url);

You can even pass a URL directly to the attr() method, instead of using a variable.

Second Way

 window.location.href="http://stackoverflow.com";

You can also code like this (both are same internally):

window.location="http://stackoverflow.com";

If you are curious about the difference between window.location and window.location.href, then you can see that the latter one is setting href property explicitly, while the former one does it implicitly. Since window.location returns an object, which by default sets its .href property.

Third Way

There is another way to redirect a page using JavaScript, the replace() method of window.location object. You can pass a new URL to the replace() method, and it will simulate an HTTP redirect. By the way, remember that window.location.replace() method doesn't put the originating page in the session history, which may affect behavior of the back button. Sometime, it's what you want, so use it carefully.

// Doesn't put originating page in history
window.location.replace("http://stackoverflow.com");

Fourth Way

like attr() method (after jQuery 1.6 introduce)

var url = "http://stackoverflow.com";
$(location).prop('href', url);

@RuNpiXelruN 2017-07-19 11:01:02

If you want to redirect to a route within the same app simply

window.location.pathname = '/examplepath'

would be the way to go.

@lalithkumar 2015-05-22 05:18:11

Javascript:

window.location.href='www.your_url.com';
window.top.location.href='www.your_url.com';
window.location.replace('www.your_url.com');

Jquery:

var url='www.your_url.com';
$(location).attr('href',url);
$(location).prop('href',url);//instead of location you can use window

@ESR 2017-08-10 05:00:02

Is there a reason for storing the url in jQuery as a variable, but not with Vanilla?

@sneha 2017-02-09 06:34:03

<script type="text/javascript">
    if(window.location.href === "http://stackoverflow.com") {      
         window.location.replace("https://www.google.co.in/");
       }
</script>

@ochi 2017-02-09 07:17:31

OP wants to know how to do it in jQuery - this does not use jQuery so it does not answer the OP's question

@Nadeem Yasin 2012-10-30 12:15:29

But if someone wants to redirect back to home page then he may use the following snippet.

window.location = window.location.host

It would be helpful if you have three different environments as development, staging, and production.

You can explore this window or window.location object by just putting these words in Chrome Console or Firebug's Console.

@moala 2014-01-17 00:21:28

window.location.replace(window.location.protocol + "//" + window.location.host)

@Iftah 2014-06-21 23:56:02

even simpler: window.location = '/'

@Rob Quist 2016-01-26 13:18:59

Iftah - that is dependant on the "base" meta tag.

@cascading-style 2016-11-23 16:42:09

Use:

function redirect(a) {
    location = a
}

And call it with: redirect([url]);

There's no need for the href after location, as it is implied.

@SantoshK 2016-10-24 09:26:27

You can redirect the page by using the below methods:

  1. By using a meta tag in the head - <meta http-equiv="refresh" content="0;url=http://your-page-url.com" />. Note that content="0;... is used for after how many seconds you need to redirect the page

  2. By using JavaScript: window.location.href = "http://your-page-url.com";

  3. By using jQuery: $(location).attr('href', 'http://yourPage.com/');

@1j01 2017-03-09 17:30:20

There is no reason to use jQuery for this and window. is unnecessary.

@SantoshK 2017-03-10 11:23:18

Where i have used window. in jquery Query Example ? ... if you want to redirect the page through javascript ... than you need to use window.location..

@1j01 2017-03-16 23:34:05

I meant those as separate things: you shouldn't use jQuery for this, and in the JavaScript example, you can simplify window.location.href = to location.href = or even location =.

@SantoshK 2017-03-21 11:01:48

Yes location.href = would be better option to redirect the page -:)

@Abhishek K. Upadhyay 2016-09-30 12:15:08

This is very easy to implement. You can use:

window.location.href = "http://www.example.com/";

This will remember the history of the previous page. So one can go back by clicking on the browser's back button.

Or:

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

This method does not remember the history of the previous page. The back button becomes disabled in this case.

Related Questions

Sponsored Content

38 Answered Questions

[SOLVED] How do you get a timestamp in JavaScript?

84 Answered Questions

[SOLVED] How to validate an email address in JavaScript

35 Answered Questions

[SOLVED] How do I return the response from an asynchronous call?

57 Answered Questions

[SOLVED] How do I include a JavaScript file in another JavaScript file?

31 Answered Questions

[SOLVED] How do I make a redirect in PHP?

  • 2009-04-20 14:13:22
  • Sam
  • 2613265 View
  • 1170 Score
  • 31 Answer
  • Tags:   php redirect

34 Answered Questions

23 Answered Questions

[SOLVED] How can I refresh a page with jQuery?

31 Answered Questions

31 Answered Questions

[SOLVED] How to manage a redirect request after a jQuery Ajax call

6 Answered Questions

[SOLVED] How do I redirect with JavaScript?

  • 2011-01-20 08:08:18
  • Ms_Lucky13
  • 1353625 View
  • 913 Score
  • 6 Answer
  • Tags:   javascript redirect

Sponsored Content