最近项目中有个需求是,浏览器上的web页面需要像移动端app一样,可以发送通知告知用户,主要的目的是为了加深与用户的粘性,提高用户的互动。经过了解发现,实现这这个功能主要是需要pwa的相关两个技术
Web Notification API
和Web Push API
1、Notification API
Notification
主要用途可以让浏览器web页面发送通知,即使当前不在同一个tab中,或者浏览器最小化等,都可以通过发送消息,然后快速打开对应网址- 关键方法和属性
Notification.requestPermission()
,主要是用来请求用户允许通知的权限Notification.permission
- 1、
granted
: 用户已经明确的授予了显示通知的权限 - 2、
denied
: 用户已经明确的拒绝了显示通知的权限。 - 3、
default
: 用户还未被询问是否授权; 这种情况下权限将视为denied
- 1、
- title、actions、body、data、image、icon等都是设置显示通知的相关展示样式
- 回调事件的处理click、close、error、show
- 简单收到通知例子如下:
<body>
<script>
function notifyMe() {
if (!("Notification" in window)) {
// Check if the browser supports notifications
alert("This browser does not support desktop notification");
} else if (Notification.permission === "granted") {
// Check whether notification permissions have already been granted;
// if so, create a notification
const notification = new Notification("Hi there!");
notification.onclick = function (event) {
event.preventDefault(); // prevent the browser from focusing the Notification's tab
window.open('http://www.mozilla.org', '_blank');
}
// …
} else if (Notification.permission !== "denied") {
// We need to ask the user for permission
Notification.requestPermission().then((permission) => {
// If the user accepts, let's create a notification
if (permission === "granted") {
const notification = new Notification("Hi there!");
notification.onclick = function (event) {
event.preventDefault(); // prevent the browser from focusing the Notification's tab
window.open('http://www.mozilla.org', '_blank');
}
// …
}
});
}
// At last, if the user has denied notifications, and you
// want to be respectful there is no need to bother them anymore.
}
</script>
<button onclick="notifyMe()">Notify me!</button>
</body>
复制代码
2、ServiceWorker 的通知
- ServiceWorker注册完后,会返回
registration
对象,该对象中有两个用于通知的方法getNotifications
,Promise
解析为Notification
对象列表。getNotifications
,调用消息通知
- 在ServiceWorker调用通知有点不一样,需要注册完成,且用户授权后调用
registration.showNotification()
方法,才可以进行消息提醒了,其中showNotification
,会调用Notification api
,参数基本与上面介绍相同 - 其中点击通知事件,需要在中ServiceWorker,监听
notificationclick
事件才可以实现,跟上面有点小区别
index.html页面:
<body>
<script>
function askPermission() {
return new Promise(function (resolve, reject) {
var permissionResult = Notification.requestPermission();
if (permissionResult) {
permissionResult.then(resolve, reject);
}else{
reject();
}
}).then(function (permissionResult) {
if (permissionResult !== 'granted') {
throw new Error('We weren\'t granted permission.');
}
});
}
navigator.serviceWorker.register('./sw.js').then(function (registration) {
return Promise.all([
registration,
askPermission()
])
}).then(function (result) {
var registration = result[0];
/* ===== 添加提醒功能 ====== */
document.querySelector('#notifyMe').addEventListener('click', function () {
var title = 'PWA即学即用';
var options = {
body: '邀请你一起学习',
icon: 'https://res.minigame.vip/gc-assets/mini/mini_icon.png',
actions: [{
action: 'show-book',
title: '去看看'
}, {
action: 'contact-me',
title: '联系我'
}],
tag: 'pwa-starter',
renotify: true
};
registration.showNotification(title, options);
});
})
</script>
<button id="notifyMe">Notify me!</button>
</body>
复制代码
sw.js:
self.addEventListener('notificationclick', function (e) {
var action = e.action;
console.log(`action tag: ${e.notification.tag}`, `action: ${action}`);
e.notification.close();
if (clients.openWindow)
clients.openWindow('http://www.mozilla.org');
});
复制代码
3、Web Push API
- 消息推送主要是由浏览器自己本身实现的服务,通过与后端服务和浏览器进行交互
- Push Service:可以接收网络请求,校验该请求并将其推送给合适的浏览器客户端。当用户离线时,可以帮我们保存消息队列,直到用户联网后再发送给他们。不同的浏览器厂商使用了不同的Push Service,Push Service遵循Web Push Protocol。
目前,不同的浏览器厂商使用了不同的Push Service
- 流程图
- 具体例子,可以查看这个链接glitch.com/edit/#!/pus…, 可以实现简易演示操作,通过与push service的交互,从而达到消息推送,最终再调用浏览器的通知