在JavaScript中的前GUI中获取应用程序初始化的firebase实例



我是服务工人的新手,还有javaScript的firebase网络。我想从Firebase检索有效载荷,以通过向用户通知显示。现在我正在努力解决以下问题。

什么有效

当我使用以下脚本注册服务工作者时,我将获得succeeded响应。

index.html

<p id="status"></p>
<script src="https://www.gstatic.com/firebasejs/4.3.1/firebase.js"></script>
<script>
    if ('serviceWorker' in navigator) {
        // Override the default scope of '/' with './', so that the registration applies
        // to the current directory and everything underneath it.
        navigator.serviceWorker.register('sw.js', {scope: './'}).then(function (registration) {
            // At this point, registration has taken place.
            // The service worker will not handle requests until this page and any
            // other instances of this page (in other tabs, etc.) have been
            // closed/reloaded.
            document.querySelector('#status').textContent = 'succeeded';
        }).catch(function (error) {
            // Something went wrong during registration. The service-worker.js file
            // might be unavailable or contain a syntax error.
            document.querySelector('#status').textContent = error;
        });
    } else {
        // The current browser doesn't support service workers.
        var aElement = document.createElement('a');
        aElement.href = 'http://www.chromium.org/blink/serviceworker/service-worker-faq';
        aElement.textContent = 'unavailable';
        document.querySelector('#status').appendChild(aElement);
    }
</script>

sw.js

importScripts('https://www.gstatic.com/firebasejs/4.3.0/firebase-app.js');
importScripts('https://www.gstatic.com/firebasejs/4.3.0/firebase-messaging.js');
var config = {
    apiKey: "MY_API_KEY",
    authDomain: "project-xxxxx.firebaseapp.com",
    databaseURL: "https://project-xxxxx.firebaseio.com",
    projectId: "project-xxxxx",
    storageBucket: "project-xxxxx.appspot.com",
    messagingSenderId: "xxxxx"
};
firebase.initializeApp(config);
const messaging = firebase.messaging();

messaging.setBackgroundMessageHandler(function (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'
    };
    return self.registration.showNotification(notificationTitle,
        notificationOptions);
});

问题是什么

现在我的问题是,我想使用index.html的服务工作者的messaging常数处理,因为控制台告诉我以下脚本仅在窗口上下文中工作:

未被发达的FirebaseError:消息传递:此方法可在 窗口上下文。(消息/唯一的窗口可用)。

messaging.requestPermission()
    .then(function () {
        console.log('Notification permission granted.' + messaging.getToken());
        messaging.getToken()
            .then(function (currentToken) {
                 if (currentToken) {
                     console.log(currentToken);
                 } else {
                     // Show permission request.
                     console.log('No Instance ID token available. Request permission to generate one.');
                     // Show permission UI.
                 }
             })
             .catch(function (err) {
                 console.log('An error occurred while retrieving token. ', err);
             });
         })
         .catch(function (err) {
             console.log('Unable to get permission to notify.', err);
         });

现在如何从注册中获取firebase实例,还是一个错误的理论?

服务工作者无法使用窗口上下文。也无法共享从窗口到SW的任何内容,反之亦然(因此您无法声明变量并从两者中访问)。从错误消息中,似乎Firebase库取决于窗口上下文,因此您不能在THS SW脚本中使用它们。

我不确定如何处理您要做的事情。

最新更新