-
前言
-
在 iOS 和 Android 移动设备中,Native App 向用户推送通知是很常见的行为,这是重新吸引用户访问应用最有效方法之一。然而推送通知一直被认为是 Web App 缺少的能力,
-
申请通知权限
-
为避免网站滥用 Notification 给用户造成影响,在展示桌面通知之前,首先需要向用户获取通知权限,只有获得用户授权之后,Notification API 才会生效。
-
Notification.permission
-
Notification.permission 是 Notification 的静态属性,代表通知权限的授权状态,取值包括:、
- granted:允许展现通知;
- denied:禁止展现通知;
- default:用户尚未授权,此时禁止展现通知,但可以向用户发送授权申请
/*
* 然后你就可以处理你的业务需求
*/
function main () {
if (typeof Notification === 'undefined') {
console.log(`浏览器不支持 Notification`)
return
}
if (Notification.permission === 'denied') {
console.log(`Notification 权限已被禁用`)
return
}
if (Notification.permission === 'granted') {
console.log(`Notification 可用`)
} else {
Notification.requestPermission().then(function (permission) {
if (permission === 'granted') {
console.log(`用户已授权,可展示通知`)
} else if (Notification.permission === 'denied') {
console.log(`用户已禁止`)
} else {
console.log(` 用户尚未授权,需首先向用户申请通知权限`)
}
})
}
}
-
Notification.requestPermission()
-
当用户尚未进行授权时,可以通过 Notification.requestPermission() 静态方法向用户申请通知权限
-
例子看上面
-
通知展现与交互
- 例子
const title = 'Simple Title';
const options = {
body: 'Simple piece of body text.\nSecond line of body text :)',
data: { type: 'focus-or-open-window', a: 1, url: '/test' }
};
const notification = new Notification(title, options)
以上的问题其实都很好解决,MDN 上有很多配置可以去看一下,配置啥,图标呀,图片呀,标题呀,是否强制用户交互呀,等等的操作都在MDN 有介绍,接下来的我觉得才可以看看
-
ServiceWorker 线程中展现通知
- 不知道ServiceWorker 的肯定知道PWA吧,其实是一个东西,不过我今天并不讲那个东西,我只是讲一下,如何利用ServiceWorker 和 Notification配合,当有消息通知来之后,如果当你tab 不在当前页面,就跳转到 消息通知的页面,案例可以去看一下 twitte
-
以下操作默认你已经看完上面的,并且已经配置好了 ServiceWorker 的一系列的东西
- 接下来以我做的项目为例
function focusOrOpenWindow(event) {
const url = event.notification.data.url || '/';
const urlToOpen = new URL(url, self.location.origin).href;
const promiseChain = clients
.matchAll({
type: 'window',
includeUncontrolled: true
})
.then(windowClients => {
let matchingClient = null;
for (let i = 0; i < windowClients.length; i++) {
const windowClient = windowClients[i];
if (windowClient.url === urlToOpen) {
matchingClient = windowClient;
break;
}
}
if (matchingClient) {
return matchingClient.focus();
} else {
return clients.openWindow(urlToOpen);
}
});
event.waitUntil(promiseChain);
}
self.addEventListener('notificationclick', function(event) {
event.notification.close();
const type = (event.notification.data && event.notification.data.type) || '';
switch (type) {
case 'focus-or-open-window':
focusOrOpenWindow(event);
break;
default:
// NOOP
break;
}
});
- 然后接下来 再全局挂载,比如我的是global
if ('ServiceWorker' in window) {
navigator.serviceWorker
.register('service-worker.js')
.then(function(registration) {
console.log('Service worker successfully registered.');
})
.catch(function(err) {
console.error('Unable to register service worker.', err);
});
}
- 以上代码的意思是,通知你是那个页面给你通知了,url就是告诉你地址,如果你是在当前页面就保留当前,如果你不是在当前页面,就跳转到你对应的通知页面,你可以直接复制过去用,不懂可以问我,