You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Django项目注册Service Worker遇"window is not defined"错误求助

Fixing "window is not defined" in Django Service Worker Setup

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 window with self in your Service Worker code
    In the Service Worker global scope, self refers 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 like document, localStorage, or location.href directly. Instead:

    • Use the caches API for caching assets
    • Use IndexedDB instead of localStorage for persistent data
    • Use self.registration to access the Service Worker's registration details
  • Double-check your Django setup
    Make sure your sw.js URL route in Django is correctly configured:

    • Ensure the view returns the Service Worker script with the correct Content-Type header (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)

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.22 07:54:38