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?
You should use
ofinstead ofin.This is probably a legacy thing, as coffeescript used
infor array iteration andoffor objects. These presence operators were made to match the existing iterator syntax, which makes it the opposite of the javascript ofinfor objects andoffor arrays.Personally I would use
if navigator?.serviceWorkeras the JSindoesn'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 useinif you prefer.From the docs on coffeescript.org: