Reputation: 102439
How can I redirect the user from one page to another using jQuery or pure JavaScript?
Upvotes: 7696
Views: 8058815
Reputation: 104870
Basically jQuery is just a JavaScript framework and for doing some of the things like redirection in this case, you can just simply use pure JavaScript, so in that case you have 3 options using vanilla JavaScript:
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");
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");
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:
Upvotes: 221
Reputation: 8838
JavaScript is very extensive. If you want to jump to another page you have these three options.
// Navigates to 'otherpage.com' and keeps the current page in the browser history.
window.location.href = 'otherpage.com';
// Navigates to 'otherpage.com' but behaves like href (keeps history); allows more control (e.g., appending query params dynamically).
window.location.assign('otherpage.com');
// Navigates to 'otherpage.com' and replaces the current page in the browser history (no back button functionality).
window.location.replace('otherpage.com');
As you want to move to another page, you can use any one from these options if this is your requirement.
However all three options are limited to different use cases. Choose as per your requirement.
If you are interested in more information about the topic, 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
window.location.replace; // Replace the current location with new one.
Upvotes: 64
Reputation: 240084
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("https://stackoverflow.com");
// similar behavior as clicking on a link
window.location.href = "https://stackoverflow.com";
Upvotes: 16410
Reputation: 4948
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.example/"/>
<noscript>
<meta http-equiv="refresh" content="0;URL=https://yourdomain.example/">
</noscript>
<!--[if lt IE 9]><script type="text/javascript">var IE_fix=true;</script><![endif]-->
<script type="text/javascript">
var url = "https://yourdomain.example/";
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 -->
Upvotes: 278
Reputation: 3789
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
The location.assign()
method loads a new document in the browser window.
window.location.assign("http://stackoverflow.com");
The difference between assign()
and replace()
method is that the location.replace()
method deletes the current URL from the document history, so it is unable to navigate back to the original document. You can't use the browsers Back button in this case. If you want to avoid this situation, you should use location.assign()
method, because it loads a new Document in the browser.
Fifth Way
like attr() method (after jQuery 1.6 introduce)
var url = "http://stackoverflow.com";
$(location).prop('href', url);
Upvotes: 53
Reputation: 3561
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.example/" />
META Location
<meta http-equiv="location" content="URL=http://evil.example" />
BASE Hijacking
<base href="http://evil.example/" />
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.
Upvotes: 189
Reputation: 47614
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).prop('href', 'http://stackoverflow.com')
Upvotes: 1837
Reputation: 3169
# HTML Page Redirect Using jQuery/JavaScript Method
Try this example code:
function YourJavaScriptFunction()
{
var i = $('#login').val();
if (i == 'login')
window.location = "Login.php";
else
window.location = "Logout.php";
}
If you want to give a complete URL as window.location = "www.google.co.in";
.
Upvotes: 101
Reputation: 67161
window.location.href = 'newPage.html';
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 security 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 help tell 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;
}
}
Upvotes: 840
Reputation: 984
window.location.href="http://google.com";
window.location.replace("http://google.com");
$(location).attr('href', 'http://google.com');
jQuery.fn.redirectTo = function(url){
window.location.href = url;
}
jQuery(window).redirectTo("http://google.com");
Upvotes: 57
Reputation: 2069
Original question: "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 with 10000 lines of code. With jQuery you can connect to this code with just a line or two.
Upvotes: 90
Reputation: 4536
Using location.replace()
will redirect you, but without saving the history of the previous page. This is 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);
}
Upvotes: 20
Reputation: 900
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")';
}
Upvotes: 17
Reputation: 598
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!
Upvotes: 16
Reputation: 1316
Simply in JavaScript, you can redirect to a specific page by using the following:
window.location.replace("http://www.test.com");
Or
location.replace("http://www.test.com");
Or
window.location.href = "http://www.test.com";
Using jQuery:
$(window).attr("location","http://www.test.com");
Upvotes: 24
Reputation: 1303
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");
Upvotes: 21
Reputation: 2338
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?
Upvotes: 203
Reputation: 2870
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");
Upvotes: 82
Reputation: 15490
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')
Upvotes: 510
Reputation: 5714
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>
Upvotes: 33
Reputation: 5035
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.
Upvotes: 13
Reputation: 20196
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")
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"
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")
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,
Upvotes: 14
Reputation: 1476
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']);
}
Upvotes: 15
Reputation: 2787
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");
.
Upvotes: 6
Reputation: 26538
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>
Protocol -- Specifies the protocol name be used to access the resource on the Internet. (HTTP (without SSL) or HTTPS (with SSL))
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.
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.
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.
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).
hash -- The anchor portion of a URL, includes the hash sign (#).
With these Location object properties you can access all of these URL components
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
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.
Upvotes: 227
Reputation: 1920
If you want to redirect to a route within the same app simply
window.location.pathname = '/examplepath'
would be the way to go.
Upvotes: 10
Reputation: 3540
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
Upvotes: 47
Reputation: 445
<script type="text/javascript">
if(window.location.href === "http://stackoverflow.com") {
window.location.replace("https://www.google.co.in/");
}
</script>
Upvotes: 15
Reputation: 4534
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.
Upvotes: 242
Reputation: 628
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.
Upvotes: 14