你能用 AMP 检测 iPhone 和 Android 吗?

jam*_*and 2 amp-html

假设我有一个 APPLE 播客按钮和一个 GOOGLE 播客按钮,我想显示:

  • 苹果播客给 iPhone 用户
  • 面向 Android 用户的 GOOGLE 播客
  • 面向桌面用户

我目前正在通过 AMP 使用<amp-list>和调用动态生成的 JSON 文件来实现这一点。效果很好;但我想知道,如果有,将删除要求这三个文件的原生方式- <amp-list><amp-mustache>被加载-和动态JSON文件。

Seb*_*enz 5

您可以在 an 中检测 UA 字符串amp-script,然后相应地更新按钮:

<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>
Run Code Online (Sandbox Code Playgroud)

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