首页 > 解决方案 > 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()。通过这种方式,我正在等待那个正在工作的服务人员开始读取我的文件。

标签: javascriptworkbox

解决方案


推荐阅读