AMP
  • websites

amp-user-notification

Introduction

Use amp-user-notification to display a dismissable notification to the user. Use this to implement a dialog to notify users about cookies.

Setup

Import amp-user-notification in the header.

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

amp-user-notification requires amp-analytics to be imported as well.

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

Specify any additional CSS, default CSS class will put the amp-user-notification element in the left bottom corner.

<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>

Basic usage with local storage

By default, when the user agrees to the cookies policy, the status is saved in the local storage.

<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>

Advanced usage with a server endpoint

When using a backend solution, two parameters are available: data-show-if-href and data-dismiss-if-href. They can be used together or separatively.

  • data-show-if-href needs to point to a server-endpoint returning { "showNotification": true|false }.
  • The URL defined by data-dismiss-href will be called when the notification is dismissed.

You can find a sample backend implementation here.

If the notification has already been dismissed and the related item has been added to the localstorage, the notification will not appear even if you have configured data-show-if-href and data-dismiss-href.

<amp-user-notification id="my-notification-with-server-endpoint" class="sample-notification" layout="nodisplay" data-show-if-href="https://amp.dev/documentation/examples/components/amp-user-notification/show?timestamp=TIMESTAMP" data-dismiss-href="https://amp.dev/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 上的示例