Chrome的API通知出现问题。它无法显示通知并向控制台返回错误。我在Firefox中没有遇到此问题。
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);
notification permission status: granted index.js:25 Uncaught (in promise) TypeError: Cannot read property 'showNotification' of undefined at index.js:25
有人知道为什么我只能在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()
外,我还解决了该问题。通过这种方式,我正在等待那个服务工作者开始读取我的文件。