amp-web-push
簡介
amp-web-push 元件允許使用者訂閱網站推播通知。
設定
在標頭中匯入 amp-web-push
元件。
<script
async
custom-element="amp-web-push"
src="https://cdn.ampproject.org/v0/amp-web-push-0.1.js"
></script>
在此示範中使用了 amp-form
元件,以傳送 post 請求,以便準備和傳送通知。
<script
async
custom-element="amp-form"
src="https://cdn.ampproject.org/v0/amp-form-0.1.js"
></script>
<script async src="https://cdn.ampproject.org/v0.js"></script>
</head>
<body>
基本用法
amp-web-push
元件需要兩個額外的 HTML 檔案以及一個與 amp-web-push 相容的 Service Worker。這三個檔案組成了以下描述的配置。
<amp-web-push
id="amp-web-push"
layout="nodisplay"
helper-iframe-url="https://amp.dev.org.tw/documentation/examples/components/amp-web-push/amp-web-push-helper-frame.html"
permission-dialog-url="https://amp.dev.org.tw/documentation/examples/components/amp-web-push/amp-web-push-permission-dialog.html"
service-worker-url="https://amp.dev.org.tw/documentation/examples/components/amp-web-push/sw.js"
service-worker-scope="https://amp.dev.org.tw/documentation/examples/components/amp-web-push/"
>
</amp-web-push>
按一下訂閱小工具會彈出一個頁面,提示使用者授權通知權限,並向 Service Worker(如下配置)發出訊號,以在背景中讓使用者訂閱推播。在此範例中,我們攔截了對 onMessageReceivedSubscribe
的呼叫,並將訂閱物件儲存在 IndexedDB 中。
<amp-web-push-widget
visibility="unsubscribed"
layout="fixed"
width="500"
height="70"
>
<button on="tap:amp-web-push.subscribe">
Subscribe to Notifications
</button>
</amp-web-push-widget>
按一下取消訂閱小工具會向 Worker 發出訊號,以在背景中取消使用者訂閱推播。在此範例中,我們也將從 IndexedDB 中移除先前儲存的訂閱物件。
<amp-web-push-widget
visibility="subscribed"
layout="fixed"
width="500"
height="180"
>
<button on="tap:amp-web-push.unsubscribe">
Unsubscribe from Notifications
</button>
<form method="post" action-xhr="https://amp.dev.org.tw/documentation/examples/components/amp-web-push/send-push" target="_top">
<input type="submit" value="Send Web Push" />
<div submitting>Sending Push message...</div>
<div submit-success>Web Push sent!</div>
<div submit-error>Something went wrong.</div>
</form>
</amp-web-push-widget>
<amp-web-push-widget
visibility="blocked"
layout="fixed"
width="250"
height="80"
>
Looks like you've blocked notifications!
</amp-web-push-widget>
需要進一步說明嗎?
如果此頁面上的說明未涵蓋您的所有問題,請隨時與其他 AMP 使用者聯繫,討論您的確切使用案例。
前往 Stack Overflow 未說明的特色功能?AMP 專案強烈鼓勵您的參與和貢獻!我們希望您能成為我們開放原始碼社群的長期參與者,但我們也歡迎您針對您特別熱衷的問題做出一次性貢獻。
在 GitHub 上編輯範例