AMP

amp-web-push

說明

允許使用者訂閱網站推播通知。

 

必要指令碼

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

支援版面配置

範例

用法

開發人員撰寫根據使用者訂閱狀態顯示的小工具。小工具由 AMP 元素組成,可以像按鈕或文字連結一樣簡單。

點擊訂閱小工具會彈出一個頁面,提示使用者授與通知權限,並向 Service Worker(如下設定)發出訊號,以便在背景中讓使用者訂閱推播。點擊取消訂閱小工具會向 Worker 發出訊號,以便在背景中取消使用者訂閱推播。

<!-- A subscription widget -->
<amp-web-push-widget
  visibility="unsubscribed"
  layout="fixed"
  width="250"
  height="80"
>
  <button on="tap:amp-web-push.subscribe">Subscribe to Notifications</button>
</amp-web-push-widget>

<!-- An unsubscription widget -->
<amp-web-push-widget
  visibility="subscribed"
  layout="fixed"
  width="250"
  height="80"
>
  <button on="tap:amp-web-push.unsubscribe">
    Unsubscribe from Notifications
  </button>
</amp-web-push-widget>

設定

amp-web-push 元件需要在您的網站上進行額外整合。您需要在您的網站上上傳兩個 HTML 檔案 (已提供),以及一個與 amp-web-push 相容的 Service Worker JavaScript 檔案。這三個檔案構成以下描述的設定。

<amp-web-push
  layout="nodisplay"
  helper-iframe-url="https://example.com/helper-iframe.html"
  permission-dialog-url="https://example.com/permission-dialog.html"
  service-worker-url="https://example.com/service-worker.js"
></amp-web-push>

所有屬性皆為必要,且所有 URL 都必須以相同的來源開頭 (例如 https://example.com)。

屬性 說明
helper-iframe-url

在此下載 helper-iframe.html 並將其上傳到您的網站。

絕對 URL,以 https:// 開頭,指向上傳到您網站的已提供 HTML 檔案 helper-iframe.html

此頁面啟用 AMP 頁面與 Service Worker 之間的通訊,Service Worker 會讓使用者訂閱和取消訂閱。此頁面也有助於判斷通知權限狀態。

permission-dialog-url

在此下載 permission-dialog.html 並將其上傳到您的網站。

絕對 URL,以 https:// 開頭,指向上傳到您網站的已提供 HTML 檔案 permission-dialog.html

此頁面會以彈出式視窗開啟,並提示授與通知權限。

service-worker-url

絕對 URL,以 https:// 開頭,指向上傳到您網站的 JavaScript Service Worker 檔案。使用與 amp-web-push 相容的 Service Worker。

如果可以,請將 Service Worker 放在您網站的根目錄 (例如 your-site.com/service-worker.js) 而非子資料夾中。amp-web-push 僅限於在 Service Worker 上傳到的相同資料夾層級 (包含子資料夾) 中運作,除非 Service Worker 是以 Service-Worker-Allowed: / 的 HTTP 回應標頭提供服務。

此 Service Worker 在背景中執行,並讓使用者訂閱和取消訂閱通知。

如果您開發自訂推播解決方案,請參閱此範例,瞭解如何讓您的 Service Worker 與 amp-web-push 相容

service-worker-scope (選填)

要安裝的 Service Worker 的範圍。

屬性

visibility (必要)

描述何時顯示小工具。值可以是 unsubscribedsubscribedblocked 其中之一。

小工具最初會隱藏,直到計算出使用者的訂閱狀態為止。

驗證

請參閱 AMP 驗證器規格中的 amp-web-push 規則

需要更多協助嗎?

您已將此文件閱讀了十幾次,但它實際上並未涵蓋您的所有問題?也許其他人也有同樣的感覺:在 Stack Overflow 上與他們交流。

前往 Stack Overflow
發現錯誤或缺少功能?

AMP 專案強烈鼓勵您的參與和貢獻!我們希望您能成為我們開放原始碼社群的長期參與者,但我們也歡迎針對您特別感興趣的問題提供一次性的貢獻。

前往 GitHub