CoffeeScript and Service Workers

39 Views Asked by At

When trying to register a service worker in CoffeeScript, it looks like the latest Chrome browser doesn't support service workers, which I know is not true. Here is my app.coffee, which is converted to JavaScript and loaded on my web page:

registerServiceWorker = () =>
    if 'serviceWorker' in navigator
        await navigator.serviceWorker.register '/service-worker.js'
        console.log "Service Worker Registered"
    else
        console.log "No service worker support"

registerServiceWorker()

And here is the resulting JavaScript:

// Generated by CoffeeScript 2.7.0
(function() {
  var registerServiceWorker,
    indexOf = [].indexOf;

  registerServiceWorker = async() => {
    if (indexOf.call(navigator, 'serviceWorker') >= 0) {
      await navigator.serviceWorker.register('/service-worker.js');
      return console.log("Service Worker Registered");
    } else {
      return console.log("No service worker support");
    }
  };

  registerServiceWorker();

}).call(this);

The JavaScript console displays "No service worker support". My Chrome version is Version 111.0.5563.65 (Official Build) (64-bit). It's running on Windows 11.

As I suspected, if I change "if 'serviceWorker' in navigator" to "if navigator.serviceWorker", then everything works just fine. But, though I have a workaround, I'm beginning to wonder if it's safe to use "X in Y" in CoffeeScript. Does anyone have an explanation?

1

There are 1 best solutions below

0
caffeinated.tech On

You should use of instead of in.

This is probably a legacy thing, as coffeescript used in for array iteration and of for objects. These presence operators were made to match the existing iterator syntax, which makes it the opposite of the javascript of in for objects and of for arrays.

Personally I would use if navigator?.serviceWorker as the JS in doesn't check that the value isn't null or defined on a prototype. In your usecase, these exceptions don't apply, so you are safe to use in if you prefer.

From the docs on coffeescript.org:

You can use in to test for array presence, and of to test for JavaScript object-key presence.

...

a in b becomes [].indexOf.call(b, a) >= 0

a of b becomes a in b