【发布时间】:2016-10-24 16:57:38
【问题描述】:
我有一个模式,首先弹出询问用户是否想要接收特别优惠,如果他们点击是,然后我拉入推送通知的代码,以便他们可以允许通知。如果他们已经允许通知,我不希望模式弹出。我正在寻找一种方法来检查用户是否已经允许通知,使用谷歌浏览器。
【问题讨论】:
标签: javascript google-chrome push-notification notifications service-worker
我有一个模式,首先弹出询问用户是否想要接收特别优惠,如果他们点击是,然后我拉入推送通知的代码,以便他们可以允许通知。如果他们已经允许通知,我不希望模式弹出。我正在寻找一种方法来检查用户是否已经允许通知,使用谷歌浏览器。
【问题讨论】:
标签: javascript google-chrome push-notification notifications service-worker
检查 Notification 对象的permission 属性:
if (Notification.permission !== "granted") {
// ask for permission
【讨论】:
与Denys Séguret 回答的Notification.permission 一起,还有更新、支持较少但更通用的Permissions API.
这是一个基于the one from MDN:的快速使用示例
function handlePermission() {
return navigator.permissions
.query({name:'notifications'})
.then(permissionQuery)
.catch(permissionError);
}
function permissionQuery(result) {
console.debug({result});
var newPrompt;
if (result.state == 'granted') {
// notifications allowed, go wild
} else if (result.state == 'prompt') {
// we can ask the user
newPrompt = Notification.requestPermission();
} else if (result.state == 'denied') {
// notifications were disabled
}
result.onchange = () => console.debug({updatedPermission: result});
return newPrompt || result;
}
////
handlePermission();
【讨论】: