在 Django 中使用 chrome 实现推送通知

Tev*_*K O 4 javascript django google-chrome push-notification service-worker

我已经学会使用 chrome https://developers.google.com/web/updates/2015/03/push-notifications-on-the-open-web?hl=en实现 Web 应用程序的推送通知 并成功运行博客中提到的示例代码。

不幸的是,我无法用 Django 复制成功。它永远不会进入 Service Worker 的 Ready 方法(navigator.serviceWorker.ready.then),即 Service Worker 永远不会准备好。

根据http://www.html5rocks.com/en/tutorials/service-worker/introduction/

Register 方法的一个微妙之处是 Service Worker 文件的位置。在这种情况下,您会注意到服务工作线程文件位于域的根目录下。这意味着 Service Worker 的范围将是整个源。换句话说,该服务工作人员将接收该域上所有内容的获取事件。如果我们在 /example/sw.js 注册 Service Worker 文件,那么 Service Worker 将只能看到 URL 以 /example/ 开头的页面(即 /example/page1/、/example/page2/)的 fetch 事件。

在Django中,如何将JS文件放在应用程序的根目录下?目前,服务工作者的范围是:http://127.0.0.1:8000/static/(当我使用 chrome://serviceworker-internals/ 时)

Raj*_*mon 5

按照这个方法...

  • 将文件放入文件夹sw.jstemplate
  • 配置视图作为静态文件

    #urls
    url(r'^sw(.*.js)$', views.sw_js, name='sw_js'),
    
    #views
    from django.views.decorators.cache import never_cache
    from django.template.loader import get_template
    @never_cache
    def sw_js(request, js):
        template = get_template('sw.js')
        html = template.render()
        return HttpResponse(html, content_type="application/x-javascript")
    
    Run Code Online (Sandbox Code Playgroud)