背景
最近接到一个需求,在浏览器端对接三方 Emarsys 的 消息推送 功能。通过查阅资料,了解到 Chrome 的消息推送 主要分为两块:
- 第一块是最接近
用户侧的消息通知,这是浏览器原生具备的能力,通过使用Notaificationapi来实现。 - 第二块则是
web push
实现用户侧消息弹窗
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<button onclick="notify()">通知</button>
<script>
function authorize() {
return new Promise((resolve, reject) => {
if (!window.Notification) {
console.log('浏览器不支持 Notification')
return resolve(false)
}
if (Notification.permission === "granted") {
return resolve(true)
}
Notification.requestPermission(function (status) {
return resolve(status === 'granted')
})
})
}
function notify () {
authorize().then(res => {
new Notification("通知标题111:", {
body: '通知内容',
icon: 'https://pic1.zhuanstatic.com/zhuanzh/50b6ffe4-c7e3-4317-bc59-b2ec4931f325.png'
})
})
}
</script>
</body>
</html>
代码看起来没啥问题,但是在 Chrome 里面访问,弹出授权弹窗并同意授权后就没有然后了。去 caniuse检查了 Chrome 版本也是支持的,于是换了 Firefox 浏览器也是不支持,最后换成 Safari 终于看到了消息弹窗。
然后怀疑 Mac 的 权限问题。打开 系统偏好设置 => 通知 找到对应的 App 发现 Chrome 和 Firefox 没有开启 允许通知 的权限
web push
更新中……