$74.48

How to redirect to another web page using JavaScript?

Ask a question+
12

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

add comment

10 Answers

9

JavaScript offers many ways to redirect the user to a different web page, if during the execution of your program you need to move to a different page.

The one that can be considered canonical to navigate to a new URL is:

window.location = "https://newurl.com"

If you want to redirect to a different path, on the same domain, use:

window.location.pathname = '/new'
add comment
7

Different ways to reach the window object.

The browser exposes the self and top objects, which all reference the window object, so you can use them instead of window in all the examples above:

self.location = 'https://newurl.com'

top.location = 'https://newurl.com'
add comment
6

Other options to redirect

As with most things in programming, there are many ways to perform the same operation.

Since window is implicit in the browser, you can also do:

location = 'https://newurl.com'

Another way is to set the href property of location:

window.location.href = 'https://newurl.com'

location also has anassign() method that accepts a URL, and performs the same thing:

window.location.assign('https://newurl.com')

The replace() method is different than the previous ways because it rewrites the current page in the history. The current page is wiped, so when you click the “back” button, you go back to the page that now is the last visited one.

window.location.replace('https://newurl.com')

This can be convenient in some situations.

add comment
6

301 redirect using a server-side directive

The above examples all consider the case of a programmatic decision to move away to a different page.

If you need to redirect because the current URL is old, and move the a new URL, it’s best to use server-level directive and set the 301 HTTP code to signal search engines that the current URL has permanently moved to the new resource.

This can be done via .htaccess if using Apache. Netlify does this through a _redirects file.

That’s not possible to do on the client-side.

The 301 HTTP response code must be sent from the server, well before the JavaScript is executed by the browser.

Experiments say that JavaScript redirects are interpreted by the search engines like 301 redirects. See this Search Engine Land post for reference.

Google says:

Using JavaScript to redirect users can be a legitimate practice. For example, if you redirect users to an internal page once they’re logged in, you can use JavaScript to do so. When examining JavaScript or other redirect methods to ensure your site adheres to our guidelines, consider the intent. Keep in mind that 301 redirects are best when moving your site, but you could use a JavaScript redirect for this purpose if you don’t have access to your website’s server.

add comment
6

Use an HTML meta tag

Another option is using a meta tag in your HTML:

<html>
  <head>
    <meta http-equiv="refresh"  content="0;URL=https://newurl.com/">
  </head>
</html>

This will cause the browser to load the new page once it has loaded and interpreted the current one, and not signal search engines anything. The best option is always to use a 301 server-level redirect.

add comment
2

As a different answer to those here. I just wanted to say you can redirect on a timer as well with a small javascript function.

<script>
         setTimeout(function(){
            window.location.href = 'https://www.whereeveryouwant.com';
         }, 5000);
      </script>

This is often useful incase anyone needs it

Lainrawr 295
add comment
0

If you want to redirect your page to a new location while on page load, you can use the following code. The following program shows a message for 5 second and redirected to new location.

In Javascript, you can use many methods to redirect a web page to another one. Almost all methods are related to window.location object, which is a property of the Window object. It can be used to get the current URL address (web address) and to redirect the browser to a new page.

window.location = "http://www.corelangs.com/css"
window.location.replace("http://www.corelangs.com");
window.location.assign("http://www.w3.org");
window.location.reload("http://www.yahoo.com");
window.navigate("http://www.amazone.com");

In some case, if someone wants to redirect back to home page then he may use the following javascript code.

window.location = window.location.host


    <html>
    <head>
      <script type="text/javascript">
      function loadNewDoc(){
          window.location="http://www.w3.org";
      }
      </script>
    </head>
    <body onLoad="setTimeout('loadNewDoc()', 5000)">
      <h1>This page will be redirected to new location....</h1>
    </body>
    </html>

Redirect Other page in new window
```javascript
  function outLink(ele, ind) {
      ele.addEventListener("click", function(event) {
          window.open(window.document.location.href, "_blank");
          window.document.location.href = this.getAttribute("href");
          event.preventDefault();

      });
  }
  document.querySelectorAll(".link").forEach(outLink);
Gopal Bajpai 210
add comment
0

We can use window.location property to access the url of the current page, and modify the url of the current page.
let location = window.location;
For redirecting the page we can use
location.href = “new url”;
// or we can use
location.assign(“new url”);
For redirecting without storing in history
location.replace(“new url”);
For reloading page
window.location.reload()
Force Refresh
We can pass true to force the reloaded page to come from the server (instead of cache). Alternatively, we can use the false to reload the page from the cache.
//from cache
window.location.reload();
window.location.reload(false);
// from server
window.location.reload(true);

add comment
0

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“;

Azniv Saroyan 120
add comment
0

My answer will cover how to do it for Javascript React.

This example:

import React from 'react';
import {BrowserRouter as Router,Route,
 Redirect,Switch} from 'react-router-dom';import Home from './App.js';
import Tutorials from './tutorials.js';

function Routes(){
    return (
    <Router>
      <div>
        <Switch>
           <Route path="/" component = {Home}>
           <Redriect from='/blog/' to="/tutorials/" ></Redriect>           <Route path="/tutorials/" component={About} ></Route>
        </Switch>
      </div>
    </Router>
    )
}

This shows that if any user visits blog they will be redirected to the tutorials page instead. Cleaner to use the react router instead of something like window.location if you are already using react.

Lainrawr 295
add comment

Your Answer