Search code examples
amp-html

Can you detect iPhone vs Android with AMP?


Let's say I have an APPLE PODCASTS button and a GOOGLE PODCASTS button, and I'd like to show:

  • APPLE PODCASTS to iPhone users
  • GOOGLE PODCASTS to Android users
  • BOTH to desktop users

I'm currently achieving this with AMP by using <amp-list> and calling a dynamically-produced JSON file. That works fine; but I'm wondering if there's a native way that would remove the requirement for these three files - <amp-list>, <amp-mustache> and the dynamic JSON file - to be loaded.


Solution

  • You can detect the UA string in an amp-script and then update the buttons accordingly:

    <amp-script layout="fixed-height" height="50"
      script="user-agent-script">
      <button id="android" hidden>Android</button>
      <button id="iOS" hidden>iOS</button>
    </amp-script>
    
    <script id="user-agent-script"
      type="text/plain"
      target="amp-script">
    
      function getMobileOS() {
        const userAgent = navigator.userAgent;
        if (/android/i.test(userAgent)) {
          return "android";
        }
        // iOS detection from: http://stackoverflow.com/a/9039885/177710
        if (/iPad|iPhone|iPod/.test(userAgent) && !window.MSStream) {
          return "ios";
        }
    
        return "other";
      }
    
      const androidButton = document.querySelector('#android');
      const iosButton = document.querySelector('#ios');
    
      const os = getMobileOS();
      if (os === 'android') {
        androidButton.removeAttribute('hidden');
      } else if (os === 'ios') {
        ios.removeAttribute('hidden');
      } else {
        androidButton.removeAttribute('hidden');
        ios.removeAttribute('hidden');
      }
    
    </script>
    

    Sample: https://amp.dev/documentation/examples/components/amp-script/#detecting-android-vs-ios-in-amp