首页 > 解决方案 > 两个服务人员在一个文件中

问题描述

我不知道我这样做是对的还是有另一种方法。我有一个用于缓存的服务工作者,我也需要实现 Firebase 云消息传递,这需要一个服务工作者。我的第一个服务人员在我的项目的根目录中,我有这个。

importScripts('https://storage.googleapis.com/workbox-cdn/releases/4.3.1/workbox-sw.js');
if (workbox) {
  workbox.precaching.precacheAndRoute([
  {
    "url": "icon-128x128.png",
    "revision": "af75a93ca2c343f1129dd7ee02fd4da7"
  },
  {
...
 }
]);



workbox.routing.registerRoute(
 /^\/$/,
  new workbox.strategies.NetworkFirst({
    cacheName: 'static-resources',
  })
);

workbox.routing.registerRoute(
 /^\/([^/]+\.htm)$/,
  new workbox.strategies.NetworkFirst({
    cacheName: 'static-resources',
  })
);


/**

  workbox.routing.registerRoute(
  /\.(?:js|css)$/,
  new workbox.strategies.StaleWhileRevalidate({
    cacheName: 'static-resources',
  })
);
**/

  workbox.routing.registerRoute(
  /\.(?:js|css)$/,
  new workbox.strategies.StaleWhileRevalidate({
    cacheName: 'static-resources',
  })
);




workbox.routing.registerRoute(
  // Cache image files.
  /\.(?:png|jpg|jpeg|svg|gif)$/,
  // Use the cache if it's available.
  new workbox.strategies.CacheFirst({
    // Use a custom cache name.
    cacheName: 'image-cache',
    plugins: [
      new workbox.expiration.Plugin({
        // Cache only 50 images.
        maxEntries: 50,
        // Cache for a maximum of a week.
        maxAgeSeconds: 7 * 24 * 60 * 60,
      })
    ],
  })
);
 console.log(`Yay! Workbox is loaded `);

} else {
  console.log(`Boo! Workbox didn't load `);
}

现在我还需要 FCM 的服务人员,里面应该有这个

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

if (firebase) {

// Initialize the Firebase app in the service worker by passing in the
// messagingSenderId.
firebase.initializeApp({
   'messagingSenderId': '14******4'
});

// Retrieve an instance of Firebase Messaging so that it can handle background
// messages.
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: '/icon-128x128.png'
  };

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

我将它们组合成一个服务人员,但似乎存在问题,因为它注册sw.js了我拥有的服务人员的名称,并且还尝试注册firebase-messaging-sw.js不成功,因为我什至没有文件。

从文档中说

register() 方法的一个微妙之处是服务工作者文件的位置。在这种情况下,您会注意到服务工作者文件位于域的根目录。这意味着服务工作者的范围将是整个源。换句话说,这个 service worker 将接收这个域上所有东西的 fetch 事件。如果我们在 /example/sw.js 中注册 service worker 文件,那么 service worker 只会看到 URL 以 /example/ 开头的页面(即 /example/page1/、/example/page2/)的 fetch 事件。

现在,因为我似乎需要在根目录中拥有用于缓存和 fcm 的服务工作者。我该怎么做?

我有这个来注册服务人员

<script>
  if ('serviceWorker' in navigator) {
     console.log('Service Worker is supported');
    window.addEventListener('load', () => {
      navigator.serviceWorker.register("/sw.js")
        .then(registration => {

          console.log(`Service Worker registered! Scope: ${registration.scope}`);
        })
        .catch(err => {
          console.log(`Service Worker registration failed: ${err}`);
        });
    });
  }
</script>

标签: javascriptfirebasefirebase-cloud-messagingservice-worker

解决方案


好吧,我刚刚将我的服务工作人员文件重命名firebase-messaging-sw.js为两个工作人员,并且它注册了两个工作人员。它对我有用。


推荐阅读