簡體   English   中英

如何在 Service Worker 中使用其他 js 文件?

[英]How do I use other js files in a service worker?

如何在 Service Worker 中使用其他 js 文件? 我不知道將我的本地 js 文件包含到我的服務工作者中的正確方法。

index.html 中的消息處理程序

 <script src="pushjs\push.min.js"></script>
 <script src="pushjs\serviceWorker.min.js"></script>
messaging.onMessage(function (payload){
            console.log("new message: " +payload);
            //Push.create(payload.data.title);
             console.log(payload.data.title);
             console.log(payload.data.message);

              var notifTitle = payload.data.title;
              var notifMessage = payload.data.message;
              console.log(notifTitle);
              console.log(notifMessage);


                Push.create(notifTitle, {
                    body: notifMessage,
                });
             

          });

firebase-messaging-sw.js 中的后台消息處理程序

messaging.setBackgroundMessageHandler(function(payload){
    console.log(payload);

                //Push.create(notifTitle, {
                //    body: notifMessage,
                //});
                // I would want to also use this here


     
})

給你兩個答案:

  1. 現在,在現代環境中,我認為您可以通過在調用中包含 options 對象來register type: "module" ,這意味着您可以使用import ,從而使您的 service worker 成為一個模塊

     import { something } from "./somewhere.js";
  2. Service Worker 的全局作用域是一個ServiceWorkerGlobalScope ,它實現了WorkerGlobalScope ,它有一個importScripts函數,你可以用它來將腳本加載到 worker 中。 這是最后一個鏈接中的示例:

     self.importScripts('foo.js'); self.importScripts('foo.js', 'bar.js', ...);

為了將腳本加載到 SW 范圍內,您需要使用importScripts()

importScripts('https://yourdomain.com/push.min.js');

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM