google-chrome - 获得 chrome 通知的权限
问题描述
我正在尝试从我的用户那里获得这样的通知许可
但是,此代码不会发送权限请求
function notifyMe() {
// Let's check if the browser supports notifications
if (!("Notification" in window)) {
alert("This browser does not support desktop notification");
}
// Let's check if the user is okay to get some notification
else if (Notification.permission === "granted") {
// If it's okay let's create a notification
var notification = new Notification("Hi there!");
}
// Otherwise, we need to ask the user for permission
// Note, Chrome does not implement the permission static property
// So we have to check for NOT 'denied' instead of 'default'
else if (Notification.permission !== 'denied') {
Notification.requestPermission(function (permission) {
// Whatever the user answers, we make sure we store the information
if(!('permission' in Notification)) {
Notification.permission = permission;
}
// If the user is okay, let's create a notification
if (permission === "granted") {
var notification = new Notification("Hi there!");
}
});
} else {
alert(`Permission is ${Notification.permission}`);
}
}
只是说“权限被拒绝”
是因为我使用的是codepen吗?
解决方案
这不是因为您使用 CodePen - 不是直接使用。这是因为您试图从跨域 iframe 请求通知权限,而 Chrome 和 Firefox(可能还有其他浏览器)不允许这样做,如文档中所述:
我们不再在此页面上显示实时示例,因为 Chrome 和 Firefox 不再允许从跨域 <iframe> 请求通知权限,而其他浏览器将跟随。
为了证明它是一个跨域浏览器,你可以在开发工具中看到src
CodePen 上的 iframe 的属性指向,https://cdpn.io/
并且 iframe 本身是嵌入到https://codepen.io/
域中的——这就是一个跨域 iframe。
要使其在 CodePen 上运行,您可以尝试这样做。它基本上省略了Notification.permission !== 'denied'
检查。
但总的来说,您的代码在真实浏览器中可以正常工作。您可以通过在浏览器的控制台中粘贴您的函数然后运行它来确认这一点。
推荐阅读
- python - 仅在 CPU 上运行 TensorFlow
- c# - 如何从颜色的原始字节数组中获取部分图像?
- python - 高效计算多个张量内积
- pandas - 熊猫没有将值作为新列附加到同一行,而是添加一个新列和新行
- macros - 在带有修改列表的宏中使用 unquote_splicing
- python - 如何让 Selenium 测试正常工作?
- android - Android NetworkStats 类中的数据使用计算
- r - 从长到宽的非分类值重塑
- java - 从方法参数中捕获 Java 8 lambda 可变变量?
- laravel - Laravel,VueJS [Vue 警告]:未知的自定义元素:您是否正确注册了组件?