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.js.cn/documentation/examples/components/amp-user-notification/show?timestamp=TIMESTAMP" data-dismiss-href="https://amp.js.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 编写