透过 Web Notifications API 可以让 Progressive Web App 发出系统层级的通知,搭配 service worker 背景执行的特性,就可以做到 App 的背景推播通知。
首先网页须被配置在 https 的环境下,再来当浏览器透过 API 操作到网页本身以外的东西都需要权限,像是位置、镜头、麦克风、系统通知等都是。
原则上也是只要 Notification
有存在就可以要求权限并使用,另外透过 Notification.permission
可以查看目前状态,要求权限的程序码如下:
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 档案来直接增加配置,也可以开启相关权限:
{
"permissions": {
"desktop-notification": {
"description": "Allows to display notifications on the user's desktop."
}
}
}
要求通知权限 (图片来源: https://blog.chromium.org/)
使用上也没有太过复杂,就是 new 一个 Notification 就完成了。
const n = new Notification("哈罗!");
const notification = new Notification("复杂一点", {
body: "描述",
icon: "/icon.png",
});
视觉设计上主要有以下几种参数,直接参考图片:
通知视觉参数对照 (图片来源: https://developers.google.com)
{
"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/
虽然目前已经有了通知的 API 但对於以时间 (time-based) 为触发条件的事件相对还没有那麽方便,Notification trigger 就是为了解决这个问题而出现的 API,未来也可能会有以地点为条件的触发 API。
目前这个 API 还是实验性的功能,需要自行从 Chrome about://flags
中开启权限,将 #enable-experimental-web-platform-features
开启。
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/
一个好的时机是在用户完成关键行为或转换後才进行提示,或是透过勾选的选项来触发。
在用户完成关键行为或转换後才透过提示手动触发 (图片来源: https://developers.google.com)
透过选项让用户手动触发 (图片来源: https://developers.google.com)
RGB调色盘:view + slider * 3 + textfield * 3 昨天介绍了每个物件...
前一篇有提到如果遇到物件格式的资料要如何做验证这个问题,事实上这个解法只需要使用 DTO、Valid...
VScode: Step 1 开启index.html存挡 Step 2 开启all.js存挡 St...
今天主要会说明 Dart 各种变数宣告的方法及 Dart 的基本型别。 变数宣告 dart主要有四种...
今天要让电脑说泥豪 printf() stdio.h 中的函式,可以把 字串 显示到程序的视窗上 字...