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 定義的網址。

您可以在 此處 找到範例後端實作。

如果通知已關閉,且相關項目已新增至本機儲存空間,即使您已設定 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.dev.org.tw/documentation/examples/components/amp-user-notification/show?timestamp=TIMESTAMP" data-dismiss-href="https://amp.dev.org.tw/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 上編輯範例