我在渐进式 Web 应用程序中将新的 Web 推送 API 与服务工作人员一起使用,但担心用户在最初启用推送通知权限后会禁用它。
检测用户禁用通知权限(即添加检测/分析)以便我可以跟踪此情况的最佳方法是什么?
最佳答案
我相信您正在寻找的内容已包含在 Permissions API 中,其中包括 change
事件。该事件会在用户最初决定时触发,并且在用户后来改变主意时再次触发。
最基本的,你可以这样做:
if ('permissions' in navigator) {
navigator.permissions.query({name:'notifications'}).then(function(notificationPerm) {
// notificationPerm.state is one of 'granted', 'denied', or 'prompt'.
// At this point you can compare notificationPerm.state to a previously
// cached value, and also listen for changes while the page is open via
// the onchange handler.
notificationPerm.onchange = function() {
// Permissions have changed while the page is open.
// Do something based on the current notificationPerm.state value.
};
});
}
有一些很好的资源展示了如何使用它:
- https://developers.google.com/web/updates/2015/04/permissions-api-for-the-web
- https://developer.mozilla.org/en-US/docs/Web/API/Permissions_API
- https://github.com/GoogleChrome/samples/tree/gh-pages/permissions
Chrome 从版本 43 开始支持 Permissions API,Firefox 从即将发布的版本 45 开始支持。
关于push-notification - 如何衡量从我的渐进式网络应用程序禁用推送通知的人数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34657517/