navrag
navrag

Reputation: 99

Redirect Safari To Chrome

I'm trying to redirect user's of my mobile webapp to use Chrome rather than Safari. I tried using the following:

<script>
javascript:location.href="googlechrome"+location.href.substring(4);
</script>

However this constantly opens tabs in Chrome in a loop. Do you know how I can successfully do this?

Cheers, Dara

Upvotes: 2

Views: 1706

Answers (2)

Katana314
Katana314

Reputation: 8610

Well, the reason is pretty obvious; Chrome is instructed to open Chrome too. You just want a userAgent conditional.

if (navigator.userAgent.indexOf("CriOS") == -1) {
  location.href="googlechrome"+location.href.substring(4);
}

I would go on my standard rant about user agent checking being bad, but I trust what you're saying about this being a private webapp. Since iOS doesn't let you change your default browser, I guess this is a fair workaround.

Upvotes: 1

machinehead115
machinehead115

Reputation: 1657

This will cause the page to open every time the webpage is loaded, regardless if you are in Safari or Chrome. This is also very poor User Experience to just forward the user to another browser without their input.

It would be better to have some way for the user to open your site in Chrome and also to have an explanation why it is needed.

There are other schemes for https and callbacks: https://developer.chrome.com/multidevice/ios/links#uri_schemes

<p>This webapp is best viewed in Google Chrome</p>
<button type="button" onclick="openInChrome()">Open in Chrome</button>
<script>
    var openInChrome = function() {
        if (/^((?!Chrome).)*(Safari)+.*$/.test(navigator.userAgent)) {
            var protocol = location.href.substring(0,location.href.indexOf(':'));
            var url = location.href.substring(location.href.indexOf(':'));

            if (protocol === "http") {
                location.href = "googlechrome" + url;
            }
            else {
                location.href = "googlechromes" + url;
            }
        }
    }
</script>

Edit:

Added a check to verify they are in Safari.

Upvotes: 5

Related Questions