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

Implementing push notification using chrome in Django

我学会了使用 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/

One subtlety with the register method is the location of the service worker file. You'll notice in this case that the service worker file is at the root of the domain. This means that the service worker's scope will be the entire origin. In other words, this service worker will receive fetch events for everything on this domain. If we register the service worker file at /example/sw.js, then the service worker would only see fetch events for pages whose URL starts with /example/ (i.e. /example/page1/, /example/page2/).

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

按照这个方法...

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

    #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")
    

与已接受的答案相似,但更短:

  • service_worker.js 放入 template 文件夹的根目录。
  • 添加到您的路线:

    from django.conf.urls import url
    from django.views.generic import TemplateView
    
    urlpatterns = [
        # Other urls
        url(r'^service_worker(.*.js)$',
            TemplateView.as_view(template_name='service_worker.js', 
                content_type='application/x-javascript'))
        ]
    

Update:我最终需要将身份验证凭证传递给 service_worker.js 文件,所以这是我的 final 路线:

url(r'^service_worker(.*.js)(?:/(?P<params>[a-zA-Z]+)/)?', 
        TemplateView.as_view(template_name='service_worker.js', content_type='application/x-javascript'))

这允许像这样传递参数:domainbase.com/service_worker.js?foo=bar...

然后访问参数的 javascript 是:

var url_params = location.search.substring(1);
console.log(url_params);
 => "foo=bar..."