注意的是,本地測試服務是完全可以看到消息通知的,如果線上環境,必須要求https協議,否則自動視爲拒絕。
通知API可能不再從不安全的來源使用。您應該考慮將應用程序切換到安全源,比如HTTPS。見https://goo.gl/rStTGz瞭解更多細節。
js代碼:
;(function(window){
var _notification = function(){
if(Notification){
return Notification;
}
else if(navigator.webkitNotifications){
return navigator.webkitNotifications;
}
else if(navigator.mozNotification){
navigator.mozNotification.createNotification
}
else{
return null;
}
}
var requestPermission = function(notification){
//console.log(notification)
notification.requestPermission().then(function(permission) {
if (permission === 'denied') {
alert('您已拒絕消息通知,可能會影響到您的用戶體驗哦!');
return;
}
if (permission === 'default') {
alert('請選擇允許消息通知,否則可能會影響到您的用戶體驗哦!');
return;
}
// Do something with the granted permission.
var NoticeFun = function(){ }
NoticeFun.prototype.show = function(options){
try{
window.navigator.vibrate([200, 100, 200]);
}finally{
return new notification(options.title, options);
}
}
var $notice = function(options){
return new NoticeFun(options);
}
window.$notice = $notice();
});
}
var notif = _notification();
if(notif){
requestPermission(notif);
}
})(window);
html代碼:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>
消息通知測試,提示時嘗試震動提示。
<script src="./js/worker.js"></script>
<script>
setTimeout(function(){
console.log(window.$notice)
if(window.$notice){
var not = window.$notice.show({
icon: "http://img0.imgtn.bdimg.com/it/u=188877350,2916594130&fm=26&gp=0.jpg",
title: "訂單通知",
body: "您的訂單已被接單,請點擊前往查看!"
})
not.onclick = function(){
alert();
}
}
}, 3000)
setTimeout(function(){
console.log(window.$notice)
if(window.$notice){
var not = window.$notice.show({
title: "支付通知",
body: "您的訂單支付已成功!"
})
not.onclick = function(){
alert();
}
}
}, 5000)
</script>
</body>
</html>
效果如下: