javascript - chrome 通知不显示并返回错误
问题描述
我在使用 Chrome 时遇到 API 通知问题。它没有设法显示通知并将错误返回到控制台。我在使用 Firefox 时没有遇到这个问题。
index.js
document.addEventListener('DOMContentLoaded', function () {
Notification.requestPermission(function (status) {
console.log('notification permission status: ', status);
displayNotification();
});
function displayNotification() {
if (Notification.permission === 'granted') {
navigator.serviceWorker.getRegistration()
.then(function (reg) {
var options = {
body: 'Buzz! Buzz!',
icon: '/static/img/logo_menu.png',
vibrate: [200, 100, 200, 100, 200, 100, 200],
tag: 'vibration-sample'
};
reg.showNotification('Hello world !', options);
})
}
}
}, false);
错误信息
通知权限状态:已授予 index.js:25 未捕获(承诺)类型错误:无法读取 index.js:25 处未定义的属性“showNotification”
有人知道为什么我只在 Chrome 上遇到这个问题吗?
编辑 :
我没有提到,但我有一个脚本标签:
<script>
// Check that service workers are registered
if ('serviceWorker' in navigator) {
// Use the window load event to keep the page load performant
window.addEventListener('load', () => {
navigator.serviceWorker.register('sw.js');
});
}
</script>
该根sw.js
文件:
importScripts('https://storage.googleapis.com/workbox-cdn/releases/3.4.1/workbox-sw.js');
if (workbox) {
console.log(`Yay! Workbox is loaded `);
} else {
console.log(`Boo! Workbox didn't load `);
}
除了 index.js 之外,我还解决了这个问题setTimeout()
。通过这种方式,我正在等待那个正在工作的服务人员开始读取我的文件。
解决方案
推荐阅读
- ios - 如何使 UIStackView 的元素居中对齐
- user-interface - Flutter 中的 Neumorphic / neomorphic 设计
- python-3.x - github python操作在numpy上失败
- sql-server - 将列拆分为 2 列并求和
- javascript - async / await 函数的返回值
- javascript - 谷歌扩展找不到现有元素
- php - 如何将表单字段添加到不在数据库中的 php/MySQL 登录表单以通过电子邮件发送
- php - Laravel:电子邮件多次发送给一个用户
- flutter - 如何在 Flutter 的粘性标题正文中添加 Gridview
- ruby-on-rails - ActiveAdmin:将默认主题样式应用于自定义面板的自定义部分