niel rhuver yvan
niel rhuver yvan

Reputation: 43

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

How do I use other js files in a service worker? I don't know the right way to include my local js files into my service worker.

message handler in 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,
                });
             

          });

background message handler in firebase-messaging-sw.js

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

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


     
})

Upvotes: 2

Views: 2711

Answers (2)

Sebastian Kaczmarek
Sebastian Kaczmarek

Reputation: 8515

In order to load a script into the SW scope, you need to use importScripts():

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

Upvotes: 1

T.J. Crowder
T.J. Crowder

Reputation: 1075537

Two answers for you:

  1. These days, in modern environments, I think you can make your service worker a module by including the options object in your call to register with type: "module", which means you can useimport.

    import { something } from "./somewhere.js";
    
  2. The global scope of a service worker is a ServiceWorkerGlobalScope which implements WorkerGlobalScope, which has an importScripts function you can use to load scripts into the worker. Here's the example from that last link:

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

Upvotes: 2

Related Questions