Django项目注册Service Worker遇"window is not defined"错误求助
Hey there! Let's break down why you're seeing that "window is not defined" error and how to fix it.
Why the Error Happens
Service Workers don't run in the browser's main window context—they operate in a separate, background global scope. The window object is exclusive to the main browser tab, so trying to access it in your Service Worker code will throw this error every time.
Step-by-Step Solutions
Replace
windowwithselfin your Service Worker code
In the Service Worker global scope,selfrefers to the Service Worker's own global context. For example:// Bad: Uses window (will throw error) window.addEventListener('fetch', (event) => { /* ... */ }); // Good: Uses self (works in Service Worker) self.addEventListener('fetch', (event) => { /* ... */ });Avoid other window-specific APIs
Don't use browser window-only objects likedocument,localStorage, orlocation.hrefdirectly. Instead:- Use the
cachesAPI for caching assets - Use
IndexedDBinstead oflocalStoragefor persistent data - Use
self.registrationto access the Service Worker's registration details
- Use the
Double-check your Django setup
Make sure yoursw.jsURL route in Django is correctly configured:- Ensure the view returns the Service Worker script with the correct
Content-Typeheader (application/javascript) - Verify the Service Worker's scope matches your project's needs (Django's
{% url 'sw.js' %}should resolve to a path that allows the Service Worker to control your desired pages)
- Ensure the view returns the Service Worker script with the correct
Quick Example Fix
If your original Service Worker had code like this:
// This will fail window.addEventListener('install', (event) => { window.caches.open('my-cache').then((cache) => { cache.addAll(['/', '/static/css/main.css']); }); });
Update it to:
// This works self.addEventListener('install', (event) => { self.caches.open('my-cache').then((cache) => { cache.addAll(['/', '/static/css/main.css']); }); });
内容的提问来源于stack exchange,提问作者Outsider

