JavaScript: How to Redirect to Another Webpage

Introduction

Oftentimes, we need to redirect users to another website or another web page on the same site. There are several ways to redirect which include JavaScript redirection, server-side redirection, and HTML meta refresh redirection. Redirection is basically a mechanism to send users to another URL address.

The motivation to use redirection can vary, in most cases, it's because:

  • You moved to another domain for any reason, so you can redirect users to the new domain when they access the content on an older domain.

  • You have multiple pages whose content varies based on location, language, browsers, or other factors based on which you redirect users to the most suitable page.

  • You redirect unauthenticated or unauthorized users' requests to resources to a login page.

  • You send users to other pages correlated with the content of the current site.

All of these are practically achieved through the Location object that contains URL information. There are a few ways to do this, by fiddling around with different properties of the Location object. In this tutorial, we'll take a look at how to redirect a user to a different webpage in JavaScript and what to look out for to minimize the potential negative SEO impact.

The window.location Property

The window.location object denotes the current location, or rather, URL of the window/user. It's technically a read-only property, though, nevertheless, we can manipulate it by assigning new values (DOMStrings) to its properties. The windows prefix in windows.location object can be omitted since it is hierarchically located at the top of the scope.

Redirect Users with location.href

The location.href property denotes the current URL as a String. Changing the href property will automatically also navigate the user to the new href value. Changing the href property is as easy as simply assigning a new value to it:

location.href = "https://stackabuse.com/";

Note: A functionally equivalent line of code is:

windows.location = "https://stackabuse.com";

It's worth noting that you can redirect a user to a domain other than the domain they're currently on with this approach, though, security issues can arise from this, so the practice should be avoided if possible.

Redirection is typically tied to some sort of event, such as pressing a button that redirects a user to a different webpage, or other events, such as a user performing some operation on a website (uploading an image on social media, after which they're redirected to that post, for example). Let's write a simple function that redirects a user on the click of a button:

<!DOCTYPE html>
<html lang="en">
<head>
    <title>Redirection</title>
    <script type = "text/javascript">
        function Redirect() {
         window.location.href = "https://stackabuse.com/";
        }
    </script>
</head>
<body>
    <input type="button" value="Redirect Me" onclick="Redirect()"/>
</body>
</html>

Setting the href property is similar to what a mouse-click would do.

Redirect Users with location.assign()

The location.assign(url) method loads the resource in the provided url, and displays it in the window. This is actually the preferred approach to redirecting users compared to setting the href property, since it also checks for the safety of the provided url, throwing an exception if it's not a safe destination. Another benefit is that it creates a new entry in the browser's history, allowing the user to gracefully go "Back" if they'd like to.

It's also worth noting that location.assign() doesn't allow cross-origin redirection. You can only redirect to the same domain in which the call is made, which has a positive impact on security.

Other than that, it can be used in much the same way as assigning a new value to location.href. Let's rewrite our page to use the assign() function instead:

<!DOCTYPE html>
<html lang="en">
<head>
    <title>Assigning</title>
    <script type = "text/javascript">
        function Assign() {
         window.location.assign("https://stackabuse.com/");
        }
    </script>
</head>
<body>
    <input type="button" value="Redirect Me" onclick="Assign()" />
</body>
</html>

Redirect Users with location.replace()

The replace(url) method can be used to replace the current resource on the window, with the resource loaded from the url. It doesn't really redirect a user, and doesn't get stored in the browser's history. The same security-constraints exist as with the assign() method, which makes this a desirable method to use if you'd like to replace the content by another page:

<!DOCTYPE html>
<html lang="en">
<head>
    <title>Replacing</title>
    <script type = "text/javascript">
        function Replace() {
         window.location.Replace("https://stackabuse.com");
        }
    </script>
</head>
<body>
    <input type="button" value="Redirect Me" onclick="Replace()" />
</body>
</html>

It's also worth noting that the assign() method has a serious potential downside. If the user is to go back onto a page which automatically runs the assign() method, they'll be redirected back to the page they've tried going back from. They'd then enter a loop of going "back" via the Back Button, but being redirected to another page due to the assign() method.

If you're using assign(), make sure that it's not automatically called on the page, and that its invocation requires a user's action, such as invoking it on a button press. If not - use location.replace().

Free eBook: Git Essentials

Check out our hands-on, practical guide to learning Git, with best-practices, industry-accepted standards, and included cheat sheet. Stop Googling Git commands and actually learn it!

Additionally, location.replace() is the closest to an HTTP redirect, since the original link doesn't get added to the browser's history.

Security Implications and Side-Effects

The mentioned security applies to all of the methods above and it refers to the following aspects:

  • If the origin of the script that's calling the method are not the same as the origins of the current page - it will be treated as a security violation and DOMException of SECURITY_ERROR type will be thrown. That's to say, external libraries and services embedded into your own page won't be able to redirect users.
  • If the stored URL is invalid, a DOMException will be thrown.
  • If you're redirecting a user to a domain other than the domain they were already on, CORS may kick in and prevent it.

Some of the possible side-effects that could happen due to human-induced design issues are:

  • When redirection (other than replace()) occurs too quickly (i.e. in less than 3 seconds) it can break the back button on a browser. This means that each time you try to move back to the previous page, the redirection will occur once again almost immediately, creating an infinite loop.
  • It can be considered as Doorway Page(i.e pages created for SEO indexes manipulation) which is not recommended
  • Poorly planned and used redirections can cause chain redirects, redirecting between two or more pages.

Influence on SEO

There are many factors that affect SEO, and a lot of them aren't actually publicly known, lest they be abused. Though, what's certain is that poorly optimized code can make a negative impact on SEO. It can lead to longer load times, chains of redirects, or even loops. Some web crawlers may try to execute JavaScript code to get a more accurate representation of the page, but those that don’t can result in having a lower SEO “score”.

The best way to overcome these issue may be:

  • To either properly issue an HTTP redirect on the server-side with any of the redirect status codes (301..308), or to issue a 404 for the pages you no longer want to host or to redirect to.

  • To inform search engines of a duplicate page by adding <link rel="canonical" href="https://original_link"/> in the <head></head> section. This is easier to implement than doing any additional work on the server-side, but keep in mind that not all web crawlers will appreciate it.

Conclusion

In this tutorial, we've gone over how to perform a redirect using JavaScript, as well as the security implications and potential influence on SEO.

Last Updated: March 6th, 2023
Was this article helpful?

Improve your dev skills!

Get tutorials, guides, and dev jobs in your inbox.

No spam ever. Unsubscribe at any time. Read our Privacy Policy.

Project

React State Management with Redux and Redux-Toolkit

# javascript# React

Coordinating state and keeping components in sync can be tricky. If components rely on the same data but do not communicate with each other when...

David Landup
Uchechukwu Azubuko
Details

Getting Started with AWS in Node.js

Build the foundation you'll need to provision, deploy, and run Node.js applications in the AWS cloud. Learn Lambda, EC2, S3, SQS, and more!

© 2013-2024 Stack Abuse. All rights reserved.

AboutDisclosurePrivacyTerms