Outsider
Outsider

Reputation: 1236

"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?

Upvotes: 17

Views: 23272

Answers (1)

Outsider
Outsider

Reputation: 1236

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.

Upvotes: 31

Related Questions