How to Redirect Site Visitors Based on their Browser

Your website may be running some modern cutting edge features that are not compatible with some browsers (especially older/legacy browsers like Internet Explorer). Fortunately, you can use JavaScript to detect which browser your site visitors are using (or not using). You can then redirect your visitor to a version of your website that is compatible with their browser.

Redirect if a user is not using Chrome

Let’s say that the cutting edge version of your website is only 100% compatible with the Chrome browser as of now, and you want to redirect any visitor who is not using Chrome to a different version of your website to make sure they don’t have a buggy experience.

Add the following code to the <head> section of your website (or in an external .js file):

if (!!window.chrome) {
  window.location = "https://yourdomain.com"
} else {
  window.location = "https://yourdomain.com/legacy-version"
}

You may want to explain to your users why they’re getting redirected, and perhaps encourage them to use the Chrome browser if they want to experience the best version of your platform:

if (!!window.chrome) {
  window.location = "https://yourdomain.com"
  alert("You’re using Chrome")
} else {
  alert(
    "Our apologies, at the moment you have to use Chrome to use the latest version of our website. You’ll be redirected to our legacy website (don’t worry it works just fine!)."
  )
  window.location = "https://yourdomain.com/legacy-site"
}

Now any user that doesn’t use Chrome will get redirected to whatever window.location value you specify.

To see that it’s working, try opening this CodePen example Chrome, and then try opening it in e.g. Firefox, Opera, or some other browser.

If you’re going to use this in real life, make sure you remove alert("You’re using Chrome") from your code. I only added it for demonstration purposes.

You can play around with the code from this tutorial here.

Browser detection technology changes and evolves fast. Different browsers require different detection methods. It also matters which device your users are browsing on (laptop, tablet, smartphone, etc.).

To keep up with the latest on browser detection technology I recommend that you keep an eye on this active StackOverflow thread.


Has this been helpful to you?

You can support my work by sharing this article with others, or perhaps buy me a cup of coffee 😊

Kofi

Share & Discuss on