0

I just create a page to redirect users to the apps link (google play & apple store & Huawei store)

I just take code from this link

The code is:

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="utf-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no" />
    <title>Test</title>
    <script>
        function getMobileOperatingSystem() {
            var userAgent = navigator.userAgent || navigator.vendor || window.opera;
            if (/android/i.test(userAgent)) {
                return "Android";
            }
            if (/iPad|iPhone|iPod/.test(userAgent) && !window.MSStream) {
                return "iOS";
            }
            return "unknown";
        }
    </script>
</head>

<body onload="DetectAndServe()">
    <script>
        function DetectAndServe() {
            let os = getMobileOperatingSystem();
            if (os == "Android") {
                window.location.href = "https://play.google.com";
            } else if (os == "iOS") {
                window.location.href = "https://apps.apple.com";
            } else {
                window.location.href = "https://my-link.com";
            }
        }
    </script>
</body>

</html>

As we know Huawei got its own store how can I check if the device is Huawei redirect it to the Huawei link?

1 Answers1

1

You probably need to test /huawei/i.test(userAgent) for Huawei devices as device manufacturer is not the same as OS checking for android.

Make sure the test for Huawei is before the test for Android otherwise it will never match!

I would also change the function to return the app store url directly rather than check for OS and then do another user agent test for Huawei devices inside the if (os == "Android") block.

function getAppStoreUrl() {
  var userAgent = navigator.userAgent || navigator.vendor || window.opera;
  if (/huawei/i.test(userAgent)) {
    return "https://my-link.com";
  }
  if (/android/i.test(userAgent)) {
    return "https://play.google.com";
  }
  if (/iPad|iPhone|iPod/.test(userAgent) && !window.MSStream) {
    return "https://apps.apple.com";
  }
  return null;
}

function DetectAndServe() {
  let appStoreUrl = getAppStoreUrl();
  if (appStoreUrl) {
    window.location.href = appStoreUrl;
  }
}
phuzi
  • 12,078
  • 3
  • 26
  • 50