39

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
  • 499
  • 1
  • 4
  • 4

2 Answers2

30

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
  • 11,668
  • 5
  • 28
  • 48
14

Use window.self instead of self.

xlm
  • 6,854
  • 14
  • 53
  • 55
  • 6
    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
  • 20
    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
  • 3
    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
  • 3
    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
  • 3
    Downvoted because this answer is not correct and should not be rated so high. – Zoltan Magyar Jan 27 '22 at 08:34
  • UpVoted cause it solved my problem. although, to be fair, my problem *was not* the question's problem (working with a serviceworker) but rather a browser enviroment related problem. So take that into account. Since that's why so many people want to downvote it. Either way, solved my problem, so upvote. – Let Apr 13 '23 at 14:02