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 上编辑示例