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-href
和 data-dismiss-if-href
。它们可以一起使用或单独使用。
data-show-if-href
需要指向返回{ "showNotification": true|false }
的服务器端点。- 当通知被关闭时,将调用由
data-dismiss-href
定义的 URL。
您可以在此处找到一个后端实现示例。
如果通知已被关闭,并且相关项已添加到本地存储,即使您配置了 data-show-if-href
和 data-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 上编辑示例-
作者: @sebastianbenz