Firefox TypeError:ServiceWorker脚本在安装期间遇到错误

时间:2018-01-17 07:29:28

标签: javascript firefox service-worker web-push

我正在我的网站上开发网络推送通知。我关注了Google的Web Push Notifications和Mozilla的The Service Worker Cookbook

我已经在Google Chrome v50 +上进行了测试,一切正常,但在调用navigator.serviceWorker.register('./push-service-worker.js')函数时,我会在Firefox 44,45,46,52,最新的Firefox(版本57.0.4 64位)上收到以下错误

  

TypeError:范围http://localhost:9600/push-service-worker.js http://localhost:9600/的ServiceWorker脚本在安装过程中遇到错误。

这是我的代码:

在controller.js中注册ServiceWorker

navigator.serviceWorker.register('push-service-worker.js')
.then((registration) => {
  return registration.pushManager.getSubscription()
    .then((subscription) => {
      if (subscription) {
        return subscription;
      }
      var subscribeOptions = {
        userVisibleOnly: true,
        applicationServerKey: buildApplicationServerKey(),
      };
      return registration.pushManager.subscribe(subscribeOptions);
    });
})
.then((subscription) => {
  sendSubscriptionToServer(subscription);
})
.catch((err) => {
  console.log('Unable to subscribe to push: ', err);
});

推送服务worker.js

'use strict';

self.addEventListener('push', (event) => {
  var payload = event.data.json();
  var title = payload.title || 'Title';
  event.waitUntil(
    self.registration.showNotification(title, {
      body: payload.body,
      icon: './common/images/notification-icon-192x192.png',
      image: payload.image || '',
    })
  );
});

self.addEventListener('notificationclick', (event) => {
  event.notification.close();
  var urlToOpen = new URL('/', self.location.origin).href;
  event.waitUntil(
    clients.matchAll({
      type: 'window',
      includeUncontrolled: true,
    })
      .then((windowClients) => {
        var matchingClient = null;
        for (var i = 0; i < windowClients.length; i++) {
          var windowClient = windowClients[i];
          if (windowClient.url === urlToOpen) {
            matchingClient = windowClient;
            break;
          }
        }

        if (matchingClient) {
          return matchingClient.focus();
        } else {
          return clients.openWindow(urlToOpen);
        }
      })
  );
});

目录结构

./root
  ---- manifest.json
  ---- push-service-worker.js
  ---- src
       ---- controller.js

感谢您的帮助!

1 个答案:

答案 0 :(得分:3)

wanderview here说:

  

FWIW,您应该始终为每个频道使用单独的配置文件(发布/ beta / dev-edition / nightly)。我们正在努力让它像开箱即用一样工作,但尚未准备就绪。

当我为多个Firefox版本使用一个配置文件时遇到此问题。要解决此问题,请转到about:support,然后点击Refresh Firefox。如果它不起作用,您可以转到about:profiles,点击Create new profile,然后点击Launch profile in new browser