AMP
  • 网站

amp-web-push

简介

amp-web-push 组件允许用户订阅 Web 推送通知。

设置

在头部导入 amp-web-push 组件。

<script
  async
  custom-element="amp-web-push"
  src="https://cdn.ampproject.org/v0/amp-web-push-0.1.js"
></script>

此演示中使用 amp-form 组件发送 post 请求,以便准备和发送通知。

<script
  async
  custom-element="amp-form"
  src="https://cdn.ampproject.org/v0/amp-form-0.1.js"
></script>
<script async src="https://cdn.ampproject.org/v0.js"></script>
</head>

<body>

基本用法

amp-web-push 组件需要两个额外的 HTML 文件和一个与 amp-web-push 兼容的服务工作线程。这三个文件构成了下面描述的配置。

<amp-web-push
  id="amp-web-push"
  layout="nodisplay"
  helper-iframe-url="https://amp.org.cn/documentation/examples/components/amp-web-push/amp-web-push-helper-frame.html"
  permission-dialog-url="https://amp.org.cn/documentation/examples/components/amp-web-push/amp-web-push-permission-dialog.html"
  service-worker-url="https://amp.org.cn/documentation/examples/components/amp-web-push/sw.js"
  service-worker-scope="https://amp.org.cn/documentation/examples/components/amp-web-push/"
>
</amp-web-push>

单击订阅小部件会弹出一个页面,提示用户授权通知权限,并向服务工作线程(如下配置)发送信号,在后台订阅用户进行推送。在此示例中,我们拦截对 onMessageReceivedSubscribe 的调用,并将订阅对象存储在 IndexedDB 中。

<amp-web-push-widget
  visibility="unsubscribed"
  layout="fixed"
  width="500"
  height="70"
>
  <button on="tap:amp-web-push.subscribe">
    Subscribe to Notifications
  </button>
</amp-web-push-widget>

单击取消订阅小部件会向工作线程发送信号,在后台取消用户推送订阅。在此示例中,我们还将从 IndexedDB 中删除之前存储的订阅对象。

<amp-web-push-widget
  visibility="subscribed"
  layout="fixed"
  width="500"
  height="180"
>
  <button on="tap:amp-web-push.unsubscribe">
    Unsubscribe from Notifications
  </button>
  <form method="post" action-xhr="https://amp.org.cn/documentation/examples/components/amp-web-push/send-push" target="_top">
    <input type="submit" value="Send Web Push" />
    <div submitting>Sending Push message...</div>
    <div submit-success>Web Push sent!</div>
    <div submit-error>Something went wrong.</div>
  </form>
</amp-web-push-widget>
<amp-web-push-widget
  visibility="blocked"
  layout="fixed"
  width="250"
  height="80"
>
  Looks like you've blocked notifications!
</amp-web-push-widget>
需要进一步解释?

如果此页面上的解释不能涵盖您的所有问题,请随时联系其他 AMP 用户,讨论您的确切用例。

前往 Stack Overflow
未解释的功能?

AMP 项目强烈鼓励您的参与和贡献!我们希望您成为我们开源社区的持续参与者,但我们也欢迎您为自己特别感兴趣的问题提供一次性贡献。

在 GitHub 上编辑示例