32

Trying to write a Service Worker for my PWA app, caugth this error. I used Google/Mozilla samples for service workers, but, anyway.

var CACHE_NAME = 'test-cache';
var urlsToCache = [
    '/'
];

self.addEventListener('install', function (event) {
    event.waitUntil(
        caches.open(CACHE_NAME)
            .then(function (cache) {
                console.log('Opened cache');
                return cache.addAll(urlsToCache);
            })
    );
});
PandaTheSlayer
  • 421
  • 1
  • 4
  • 4

3 Answers3

25

Use window.self instead of self.

xlm
  • 5,564
  • 13
  • 48
  • 52
  • 4
    by using `window.self` the goes away. but the `addEventListener` which is doing install does not actually install the service worker – AADProgramming Mar 31 '19 at 04:52
  • 10
    I don't understand why this answer is so highly rated. The question is about accessing the global object in a ServiceWorker. Both ServiceWorkers and WebWorkers do not have `window` objects so this suggestion will not work. Accessing the global object using `self` is the correct thing to do. The rule should be disabled @Fraction points out below. – Sanborn Jan 19 '21 at 23:36
  • downvoted answer. self and window.self are not the same thing on nor-browser environments e.g. serviceworker. refer: https://stackoverflow.com/a/3638982/6196679 – Partha P. Das Jul 04 '21 at 10:24
  • I downvoted this answer. As previously stated above, workers dont have a window shortcut for the global scope. – Tor Brekke Skjøtskift Aug 05 '21 at 08:38
  • Downvoted because this answer is not correct and should not be rated so high. – Zoltan Magyar Jan 27 '22 at 08:34
18

You can explicitly remove self from the no-restricted-globals rule or simply disable the rule for the line containing self using eslint-disable-line or eslint-disable-next-line:

self.addEventListener('install', function (event) { /* eslint-disable-line no-restricted-globals */
...

Or

/* eslint-disable-next-line no-restricted-globals */
self.addEventListener('install', function (event) {
...
Fraction
  • 9,011
  • 4
  • 19
  • 38
6

Add var self = this; or use this.addEventListener(...)

dparkar
  • 1,880
  • 20
  • 51