Search code examples
ruby-on-railsservice-workerweb-push

How to fix importScripts not defined using service worker and onesignal?


I am trying to set up a web push app, with one signal notifications. I know nothing about service workers, but used rails service-workers gem. I get this error >importScripts is not defined. I have already followed this tutorial from rossta, serviceworker-rails. The error must be in OneSignalSDKWorker.js.erb.

I have already tried to change the name to OneSignalSDKWorker.js nothing seems to work. I'm working fully https on Heroku. make a function

``` funtion(){
   importScripts('https://cdn.onesignal.com/sdks/OneSignalSDKWorker.js');
};



```serviceworket-companion.js
if (navigator.serviceWorker) {
  navigator.serviceWorker.register('/serviceworker.js', { scope: './' })
    .then(function(reg) {
      console.log('[Companion]', 'Service worker registered!');
    });
}

if (navigator.serviceWorker) {
  navigator.serviceWorker.register('/OneSignalSDKWorker.js', { scope: './' })
    .then(function(reg) {
      console.log('[Companion] Onesignal worker registered!');
    });
}

if (navigator.serviceWorker) {
  navigator.serviceWorker.register('/OneSignalSDKUpdaterWorker.js', { scope: './' })
    .then(function(reg) {
      console.log('[Companion] Updater worker registered!');
    });
}
``` 

``` OneSignalSDKworker.js.erb 
importScripts('https://cdn.onesignal.com/sdks/OneSignalSDKWorker.js');
```

I hope to get user to subscribe in onesignal, but instead it only gives me that error!


Solution

  • I can see a couple potential issues.

    1) If you are attempting to importScripts from a service worker, that needs to be executed at the top of the file and not in a method. In other words, it needs to be the first thing that runs within your service worker.

    2) You are attempting to register multiple services workers which works but only if they are defined for different scopes. In the code you provided, you are registering them for the same scope which will only register one of them.