Redirect based on User Agent


#1

I don’t know JavaScript at all. However, I’ve made an Android app in which I’m using a WebView to load a webpage. I have a Share option in the menu that allows to share the URL that’s then loaded in the WebView.

For a particular page, I would like the users who are not using the app to be redirected to a different page. To make this possible, my Android app is using a custom user agent (say CustomUA, in this case). So, whenever my app loads this particular webpage (say page1.html), I want it to load normally inside the app. However, suppose the URL is shared, I would like the URL to be redirected to say page2.html if it’s visited using any browser. Basically, I want only the UA of my app to be able to access page1.html and every other UA is to be redirected to page2.html.

I suppose this can be done using JavaScript as I read some other solutions. I couldn’t implement those as they were not exactly my case and I’m not sure how to implement them. I suppose, I just have to place that script in my page’s body?

Also, just in case, if I’m supposed to include multiple user agents in the whitelist (i.e., if I want CustomUA and CustomUA 2, both to be able to access the webpage), how do I modify the code?

After a lot of research, I found this code:

if ((navigator.userAgent.indexOf('MSIE') >= 0) && (navigator.userAgent.indexOf('Opera') < 0))
{
    window.location.replace("your page");
}
else 
{
   window.location.replace("your page");
}

</script>

and I edited it to fit my needs like this:

<script type="text/javascript">
if (navigator.userAgent.indexOf('customUA') == -1)
{
window.location.replace("page2.html");
}
</script>

however, this is still not working the way it’s expected. I tried < 0, > 0, <= 0,etc., just in case they might work. But, they didn’t.

Please help me with this.


#2

What does navigator.userAgent.indexOf('customUA') actually return at that point?

You can check by setting it as a variable before the if statement, and setting it as a breakpoint you can look at the value.

<script type="text/javascript">
var uaCheck = navigator.userAgent.indexOf('customUA');
if (uaCheck == -1) { // <---- Set your breakpoint for this line, and inspect the uaCheck variable.
    window.location.replace("page2.html");
}
</script>

[Edit:]
Also, note that if uaCheck > -1, it has detected your app’s user agent, and you’d send them to the page you want for the app.


#3

10 years ago, browser detection was about 15 years out of date.

I’ll leave this link here in case it’s useful to someone. https://www.sitepoint.com/community/t/here-is-browser-detection-code-in-javascript


#4

I’m not really detecting browsers. I’ve set a custom User Agent to my app and I want to redirect if a webpage is requested without that custeom User Agent. I don’t otherwise care what browser the user is using. I don’t or won’t really consider this as out of date.


#5

So check if your user agent test is actually working properly. If the test is working properly, it might be the format of your location.replace().

If you’re not already, try giving it a full URL, instead of a relative one.


#6

Sorry for the late reply… I had to leave right after testing your suggestion. Actually, the redirect worked as expected when I set the user agent to customUA (I tried using Developer tools in Chrome). However, when I set the UA of my app in the code, the redirect doesn’t work fine. It redirects even my app page. The custom UA of my app is ‘App Name 1.0.0’ without the ‘’. Do you think that might be creating the problem? If it should not create any problems, I’ll have to check again with my app, but, as I said, I just had to leave my home, so, will run the checks later.


#7

So in your test you’d be looking for if(navigator.userAgent.indexOf('App Name 1.0.0') == -1), and that would be true if it is not your app.


#8

oooh danger Will Robinson. Danger!

This is NOT a validly true statement. The OP’s own statement proves that:

Do NOT trust User Agent to be a form of security. Or reliable. Or even present, in many cases. Make sure your code is flexible enough to handle the missing case, as well as the invalid one (hint, undefined cant be indexOf’d without the script falling over). Do not assume that “It made it here, so its my app. I can be lazy.”


#9

True, because anyone could whip up their own user agent string. There is no real way to guarantee that you are getting your own app using user agent strings. You’d likely need some sort of back-end handshake that tries to determine the authenticity of the app.


#10

Well, the issue was with me configuring the Javascript with the wrong User Agent. It turns out that I had forgotten what UA I had set in my app.

Well, about security… it’s not some secure page… it’s just a simple webpage which has different text than that of the app version. So, I guess, a simple trick is okay with me.

About users being able to change their user agents, yeah, well, I know, anyone can do that. But, they can’t do so in my Android app and secondly, I don’t think that they can know what User Agent my app is using to put that string in the web browsers (please correct me here if I’m wrong, I’m a bit new to all this). Also, my target audience isn’t much of tech savvy. But still, thank you all for the concern and the information.

Anyways, just one last thing now. As I had asked in the OP, how can I add more User Agents to the list? Do I have to copy-paste the same thing over and over with different user agents or do something else, like maybe seperate multiple user agents with a comma or something?


#11

To add a second (or third or more) check you can do

if (navigator.userAgent == undefined || navigator.userAgent.indexOf('customUA') == -1 || navigator.userAgent.indexOf('customUA2') == -1) {
    window.location.replace("page2.html");
}

Just put double-pipes (the or operator) between each.
If that list starts to get longer, you might want to break it out into its own function, an example of which follows.

function isMyAppUA(testUA) { // keep in mind that this doesn't guarantee to be your app, only what your app uses for UA
    if(testUA == undefined) return false;
    var appUAList = [
        'customUA1', 'customUA2', 'customUA3', 'customUA4' // ... and so on
    ];
    appUAList.forEach((ua) => {
        if(testUA.indexOf(ua) > -1) {
            return true;
        }
    });
    return false;
}
...
// Then you'd use the function like so:
if(!isMyAppUA(navigator.userAgent)) { // This is saying "if not my app's user agent"
    window.location.replace("page2.html");
}
...

[Edited to add in m_hutley’s suggestion for the absence of user agents]


#12

Thanks a lot!


#13

One thing to note is that any browser which has javascript disabled wouldn’t be redirected. If this is an issue, which I’m guessing it wouldn’t be in this case, then using a server side solution would be a better approach.