<!DOCTYPE html>在新建一个pushservice.js
<html>
<head>
<meta charset="UTF-8">
<link href="css/index.css" rel="stylesheet">
</head>
<body>
PWA浏览器Notification通知
<script>
if ('serviceWorker' in navigator) {
window.addEventListener('load', function() {
navigator.serviceWorker.register('pushservice.js').then(function(registration) {
Notification.requestPermission(function(result) {
if (result === 'granted') {
registration.showNotification('系统通知', {
body: '通知内容', // 内容
icon: 'images/banana.png', // 图标
badge: 'images/banana.png', // 小图标,手机上展现通知缩略信息时使用
image: 'images/banana.png', // 给用户的预览图
vibrate: [100, 200, 200, 300], // 设置震动
requireInteraction: true, // 显示通知直到用户交互
actions: [
// 给通知增加一些按钮
{
action: 'f-action',
title: '按钮1',
icon: 'images/banana.png'
},
{
action: 's-action',
title: '按钮二',
icon: 'images/banana.png'
}]
});
}
});
// Registration was successful
console.log('ServiceWorker registration successful with scope: ',
registration.scope);
}, function(err) {
// registration failed :(
console.log('ServiceWorker registration failed: ',
err);
});
});
}
// 注册后显示通知
</script>
</body>
</html>
self.addEventListener('notificationclick', function(event) {注意:这些代码必须运行在https下才能弹出提示框
let promiseChain = Promise.resolve();
if (!event.action) {
// 没有点击在按钮上
//const data = event.notification.data;
console.log('Notification click.');
return;
}
// 对应 registration.showNotification(title, options) 中 options 中设置的按钮
switch (event.action) {
case 'f-action':
console.log('f-action click');
promiseChain = clients.openWindow("http://bfw.wiki/");
break;
case 's-action':
console.log('s-action click');
break;
default:
console.log('Unknow action click', event.action);
}
event.waitUntil(promiseChain);
});
项目在线webide地址为http://studio.bfw.wiki/Studio/Open.html?projectid=15874608911762310073
网友回复