Amp html 你能用AMP检测iPhone和Android吗?

Amp html 你能用AMP检测iPhone和Android吗?,amp-html,Amp Html,假设我有一个苹果播客按钮和一个谷歌播客按钮,我想展示: 苹果向iPhone用户播客 谷歌向安卓用户播客 两者都适用于桌面用户 我目前正在使用AMP实现这一点,方法是使用并调用动态生成的JSON文件。这很好;但是我想知道是否有一种本地方式可以删除这三个文件的要求——、和动态JSON文件——要加载。您可以在amp脚本中检测UA字符串,然后相应地更新按钮: <amp-script layout="fixed-height" height="50" script="user-agent-s

假设我有一个苹果播客按钮和一个谷歌播客按钮,我想展示:

  • 苹果向iPhone用户播客
  • 谷歌向安卓用户播客
  • 两者都适用于桌面用户

我目前正在使用AMP实现这一点,方法是使用
并调用动态生成的JSON文件。这很好;但是我想知道是否有一种本地方式可以删除这三个文件的要求——
和动态JSON文件——要加载。

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

<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>

这有帮助吗:非常感谢您——这是一个多么烦人的例子(我完全错过了!)您真好,谢谢。(谢谢你给出了完整的答案,包括我想要的按钮。谢谢你。)我只是想补充一下。。。我现在把这个脚本放在了底部——我发现,最初将按钮显示为隐藏的原因是为了避免它们在amp脚本出现时闪烁,然后消失。你真好,谢谢。它已经取代了外部文件amp列表、amp小胡子、动态PHP脚本和三个外部SVG图像的加载,只需一个外部文件用于amp脚本。这五个HTTP GET命令被删除了,这尤其有益,因为动态PHP脚本无法缓存。