AMP
  • 网站

amp-user-notification

简介

使用 amp-user-notification 向用户显示可关闭的通知。 使用此功能实现一个对话框,以通知用户有关 cookie 的信息。

设置

在标题中导入 amp-user-notification

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

amp-user-notification 也需要导入 amp-analytics

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

指定任何其他 CSS,默认 CSS 类会将 amp-user-notification 元素放在左下角。

<style amp-custom>
  :root {
    --space-2: 1rem;   /* 16px */
  }
  /* Center the notification content */
  amp-user-notification.sample-notification {
    padding: var(--space-2);
    display: flex;
    align-items: center;
    justify-content: center;
  }
  amp-user-notification.sample-notification > button {
    min-width: 80px;
  }
</style>

本地存储的基本用法

默认情况下,当用户同意 cookie 政策时,该状态将保存在本地存储中。

<amp-user-notification id="my-notification" class="sample-notification" layout="nodisplay">
  This is an amp-user-notification. It uses local storage to store the dismissed state.
  <button on="tap:my-notification.dismiss">I accept</button>
</amp-user-notification>

使用服务器端点的高级用法

使用后端解决方案时,有两个参数可用:data-show-if-hrefdata-dismiss-if-href。它们可以一起使用或单独使用。

  • data-show-if-href 需要指向一个服务器端点,该端点返回 { "showNotification": true|false }
  • 当通知被关闭时,将调用 data-dismiss-href 定义的 URL。

您可以在此处找到后端实现的示例。

如果通知已被关闭,并且相关项已添加到本地存储,则即使您配置了 data-show-if-hrefdata-dismiss-href,通知也不会出现。

<amp-user-notification id="my-notification-with-server-endpoint" class="sample-notification" layout="nodisplay" data-show-if-href="https://amp.org.cn/documentation/examples/components/amp-user-notification/show?timestamp=TIMESTAMP" data-dismiss-href="https://amp.org.cn/documentation/examples/components/amp-user-notification/echo/post">
    This is an amp-user-notification. It uses a backend service to verify if the notification has to be shown.
    <button on="tap:my-notification.dismiss">I accept</button>
</amp-user-notification>
需要进一步的解释吗?

如果此页面上的说明没有涵盖您的所有问题,请随时与其他 AMP 用户联系以讨论您的确切用例。

转到 Stack Overflow
一个未解释的功能?

AMP 项目强烈鼓励您的参与和贡献!我们希望您成为我们开源社区的长期参与者,但我们也欢迎您为自己特别关注的问题做出一次性贡献。

在 GitHub 上编辑示例