Firebase 消息传递 importScripts 未定义

我在Firebase平台上写了一个WEB应用程序

I write a WEB application on the platform Firebase

我有一个文件 "firebase-messaging-sw.js",当我从 home.html 页面访问该文件时,我得到一个错误:

I have a file "firebase-messaging-sw.js", and when I access the file from home.html page, I get an error:

importScripts 不是

importScripts is not

文件 firebase-messaging-sw.js" 位于根级别.

home.html:

<html>
<head>
    <meta charset="utf-8" />
    <title></title>
    <link rel="shortcut icon" href="img/favicon.png"/>
    <meta name="keywords" content="" />

    <link rel="stylesheet" href="css/reset.css" type="text/css" />
    <link rel="stylesheet" href="css/home.css" type="text/css" media="screen and (min-width:901px)" />
    <link rel="stylesheet" href="css/mhome.css" type="text/css" media="screen and (max-width:900px)" />

</head>

<body>
    <header>
        ...
    </header>

    <div class="function">
        ...
    </div>

    <footer>
        ...
    </footer>

    <!-- The core Firebase JS SDK is always required and must be listed first -->
    <script src="https://www.gstatic.com/firebasejs/6.3.3/firebase-app.js"></script>
    <script src="https://www.gstatic.com/firebasejs/6.3.3/firebase-auth.js"></script>
    <script src="https://www.gstatic.com/firebasejs/6.3.3/firebase-firestore.js"></script>
    <script src="https://www.gstatic.com/firebasejs/6.3.3/firebase-storage.js"></script>
    <script src="https://www.gstatic.com/firebasejs/6.3.3/firebase-messaging.js"></script>
    <script src="https://www.gstatic.com/firebasejs/6.3.3/firebase-performance.js"></script>

    <script src="javaScript/initFirebase.js"></script>
    <script src="javaScript/homeFirebase.js"></script> 
    <script src="javaScript/initHomePage.js"></script> 
    <script src="javaScript/latlon-geohash.js"></script> 

    <script src="firebase-messaging-sw.js"></script>

</body>

firebase-messaging-sw.js:

firebase-messaging-sw.js:

importScripts('https://www.gstatic.com/firebasejs/6.3.3/firebase-app.js');
importScripts('https://www.gstatic.com/firebasejs/6.3.3/firebase-messaging.js');

firebase.initializeApp({
    'messagingSenderId': '123456654321'
});

帮助修复错误!谢谢!

推荐答案

firebase-messaging-sw.js 是 service worker JavaScript 文件.

firebase-messaging-sw.js is service worker JavaScript file.

所以你不应该使用 <script src="firebase-messaging-sw.js"></script> 加载 JavaScript 文件.

So you should not load JavaScript file using <script src="firebase-messaging-sw.js"></script>.

删除 <script src="firebase-messaging-sw.js"></script> 并尝试以下代码.

Remove <script src="firebase-messaging-sw.js"></script> and try the following code.

    <script>
      if ('serviceWorker' in navigator) {
        window.addEventListener('load', () => {
          navigator.serviceWorker.register('/firebase-messaging-sw.js');
        });
      }
    </script>

请参阅 https://developers.google.com/web/基础/入门/服务工作者/#register_a_service_worker

相关文章