Progressive Web App Notification Web Notifications API 應用程式通知

me
林彥成
2021-09-25 | 2 min.
文章目錄
  1. 1. 什麼是 Web Notifications API?
  2. 2. 怎麼使用 Web Notifications API?
    1. 2.1. Notifications API 參數
  3. 3. Notification Triggers
  4. 4. Permission UX

什麼是 Web Notifications API?

透過 Web Notifications API 可以讓 Progressive Web App 發出系統層級的通知,搭配 service worker 背景執行的特性,就可以做到 App 的背景推播通知。

下一篇文章小編會完整開箱怎麼實作前後端的網站推播通知

底下連結提供基本的推播示範:
https://linyencheng-push-notification.herokuapp.com/

怎麼使用 Web Notifications API?

首先網頁須被配置在 https 的環境下,再來當瀏覽器透過 API 操作到網頁本身以外的東西都需要權限,像是位置、鏡頭、麥克風、系統通知等都是。

原則上也是只要 Notification 有存在就可以要求權限並使用,另外透過 Notification.permission 可以查看目前狀態,要求權限的程式碼如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
if ("Notification" in window) {
Notification.requestPermission().then(function (result) {
console.log(result);
});
}

// 也可以寫成函式
function checkNotificationPromise() {
try {
Notification.requestPermission().then();
} catch (e) {
return false;
}

return true;
}

在已安裝的 App 中可以透過 manifest 檔案來直接增加配置,也可以開啟相關權限:

1
2
3
4
5
6
7
{
"permissions": {
"desktop-notification": {
"description": "Allows to display notifications on the user's desktop."
}
}
}

要求通知權限 (圖片來源: https://blog.chromium.org/)
要求通知權限

使用上也沒有太過複雜,就是 new 一個 Notification 就完成了。

1
2
3
4
5
const n = new Notification("哈囉!");
const notification = new Notification("複雜一點", {
body: "描述",
icon: "/icon.png",
});

Notifications API 參數

視覺設計上主要有以下幾種參數,直接參考圖片:

通知視覺參數對照 (圖片來源: https://developers.google.com)

1
2
3
4
5
6
7
8
9
{
"body": "<String>",
"icon": "<URL String>",
"image": "<URL String>",
"badge": "<URL String>",
"vibrate": "<Array of Integers>",
"sound": "<URL String>",
"dir": "<String of 'auto' | 'ltr' | 'rtl'>"
}

如果還是沒什麼感覺,底下有大大製作的產生器,直接試玩最快:
https://tests.peter.sh/notification-generator/

Notification Triggers

雖然目前已經有了通知的 API 但對於以時間 (time-based) 為觸發條件的事件相對還沒有那麼方便,Notification trigger 就是為了解決這個問題而出現的 API,未來也可能會有以地點為條件的觸發 API。

目前這個 API 還是實驗性的功能,需要自行從 Chrome about://flags 中開啟權限,將 #enable-experimental-web-platform-features 開啟。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
if ("showTrigger" in Notification.prototype) {
// 開啟後有存在就可以使用囉
// 註冊
registration.showNotification(
`Triggered for ${new Date(Date.now() + sec * 1000).toLocaleTimeString()}`,
{
tag: Math.random().toString().substr(2),
body: `Scheduled at ${new Date().toLocaleTimeString()}.`,
showTrigger: new TimestampTrigger(Date.now() + sec * 1000),
icon: icon,
}
);

const registration = await navigator.serviceWorker.getRegistration();
const notifications = await registration.getNotifications({
includeTriggered: true,
});
// 關閉全部
notifications.forEach((notification) => notification.close());
}

教學文件中 Demo 的站台: https://notification-triggers.glitch.me/

Permission UX

一個好的時機是在用戶完成關鍵行為或轉換後才進行提示,或是透過勾選的選項來觸發。

  1. 在用戶完成關鍵行為或轉換後才透過提示手動觸發 (圖片來源: https://developers.google.com)

  2. 透過選項讓用戶手動觸發 (圖片來源: https://developers.google.com)

    >


喜歡這篇文章,請幫忙拍拍手喔 🤣


share