首页 > 解决方案 > Codeigniter4 无法加载文件 firebase-messaging-sw.js 并出现错误无法执行“importScripts”

问题描述

我有一个 codeigniter4 项目来接收来自客户的通知消息。我正在使用 firebase 接收消息并已在index.php文件中成功生成了一个令牌,但文件public/firebase-messaging-sw.js无法加载,错误无法执行importScript。以下是我的编码,我的编码有什么问题或缺少吗?请帮忙谢谢。

代码 index.php

<script type="module">
        import {
            initializeApp
        } from "https://www.gstatic.com/firebasejs/9.1.3/firebase-app.js";
        import {
            getMessaging,
            getToken,
            onMessage
        } from "https://www.gstatic.com/firebasejs/9.1.3/firebase-messaging.js";

        const firebaseConfig = {
            apiKey: "xxxxxxxxxxxxxxx",
            authDomain: "xxxxxxxxxxxxxxx",
            databaseURL: "xxxxxxxxxxxxxxx",
            projectId: "xxxxxxxxxxxxxxx",
            storageBucket: "xxxxxxxxxxxxxxx",
            messagingSenderId: "xxxxxxxxxxxxxxx",
            appId: "xxxxxxxxxxxxxxx",
            measurementId: "xxxxxxxxxxxxxxx"
        };

        const app = initializeApp(firebaseConfig);
        const messaging = getMessaging();

        getToken(messaging, {
            vapidKey: 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx',
        }).then((currentToken) => {
            if (currentToken) {
                console.log('token firebase: ', currentToken)
            } else {
                console.log('No registration token available. Request permission to generate one.');
            }
        }).catch((err) => {
            console.log('An error occurred while retrieving token. ', err);
        });

        onMessage(messaging, (payload) => {
            console.log('Message received. ', payload);
        });
    </script>

代码 firebase-messaging-sw.js

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

const firebaseConfig = {
    apiKey: "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx",
    authDomain: "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx",
    databaseURL: "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx",
    projectId: "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx",
    storageBucket: "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx",
    messagingSenderId: "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx",
    appId: "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx",
    measurementId: "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
};

const app = initializeApp(firebaseConfig);
const messaging = getMessaging();

messaging.onBackgroundMessage(messaging, (payload) => {
  console.log('[firebase-messaging-sw.js] Received background message ', payload);
  // Customize notification here
  const notificationTitle = 'Background Message Title';
  const notificationOptions = {
    body: 'Background Message body.',
    icon: '/firebase-logo.png'
  };

  self.registration.showNotification(notificationTitle,
    notificationOptions);
});

在此处输入图像描述

标签: firebase-cloud-messagingcodeigniter-4

解决方案


推荐阅读