[Fixed]-"window is not defined" service worker

29πŸ‘

βœ…

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.

πŸ‘€Outsider

Leave a comment