Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

"window is not defined" service worker

I am trying to register a service worker for my django project. This is the code I am using for registration:

<!-- register service worker -->
<script type="text/javascript">
  if('serviceWorker' in navigator) {
    window.addEventListener('load', function() {
      navigator.serviceWorker.register("{% url 'sw.js' %}").then(function(registration) {
        console.log("Service worker registered.");
        console.log("Registered at: "+registration.scope);
      });
    });
  }
</script>

and this is the code in my service_worker.js:

// App install banner
window.addEventListener('beforeinstallprompt', function(e) {
  e.userChoice.then(function(choiceResult) {
    console.log(choiceResult.outcome);

    if(choiceResult.outcome == 'dismissed') {
      console.log('User cancelled home screen install');
    } else {
      console.log('User added to home screen');
    }
  });
});

I see this error in console: Uncaught ReferenceError: window is not defined

How to fix this?

like image 327
Arka Ghosh Avatar asked Apr 05 '18 05:04

Arka Ghosh


People also ask

How do you fix window is not defined?

To solve the "ReferenceError: window is not defined" error, make sure to only use the window global variable on the browser. The variable represents a window containing a DOM document and can't be used on the server side (e.g. in Node. js). If you need to define global variables in Node.

Does service worker have access to window?

You cannot use a service worker to control any window object. Service workers run in a worker context (not a browser context); it therefore has no DOM access. Since things like postMessage() is a window function, and window is part of the DOM, you cannot window. postMessage() from a service worker.

What is service worker stackoverflow?

A service worker is a specific type of JS Script, which runs in the background of the user's browser. It acts like a proxy server exists between your app, the browser and the network.


1 Answers

I was writing the code:

// App install banner
window.addEventListener('beforeinstallprompt', function(e) {
    e.userChoice.then(function(choiceResult){
        console.log(choiceResult.outcome);
        if(choiceResult.outcome == 'dismissed'){
            console.log('User cancelled home screen install');
        }else{
            console.log('User added to home screen');
        }
    });
});

in service_worker.js file. The service workers don't have access to DOM elements like window or document. Once I put the above code in a separate js file associated to the html file, it worked. I am new to PWAs and the concept of service workers and this seems like a newbie mistake. I am posting this answer should it help someone else.

like image 61
Arka Ghosh Avatar answered Oct 23 '22 18:10

Arka Ghosh