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?
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With