使用Service Worker缓存非SSL请求

时间:2016-04-02 14:08:22

标签: javascript html5 ssl offline-caching service-worker

由于Service Worker注册要求通过HTTPS投放网站,因此当我尝试将HTTP资源添加到Cache时,Google Chrome会出错:

  

混合内容:' https://example.com/sw.js'是通过HTTPS加载的,但请求了一个不安全的资源' http://example.com/'。此请求已被阻止;内容必须通过HTTPS提供。

我想缓存主HTTP页面(或至少301重定向到HTTPS),因为对于用户来说,很难键入https://部分,尤其是在移动设备上,以获取对我的缓存版本的访问权限网站,离线时。

是否有任何解决方法可以实现这一目标?

3 个答案:

答案 0 :(得分:2)

我已经考虑了一下,我认为没有直接解决你遇到的问题。跨域策略将阻止您在本地缓存它,这是有充分理由的。如果没有,您可以拦截对其他来源的任何请求。

https://developer.mozilla.org/en-US/docs/Web/API/Service_Worker_API说 “出于安全考虑,服务工作者只能通过HTTPS运行。在中间攻击中修改网络请求对人类开放是非常糟糕的。

作为一种解决方案,我将在http上托管应用程序缓存清单,并重定向到https。如果用户首次通过https进入,则不会自动缓存,但如果是这种情况,则用户很可能始终通过https访问该页面。如果用户确实使用了http,它将缓存重定向,并且可以离线使用。虽然该技术已被弃用,但仍被广泛使用,参考:https://developer.mozilla.org/en-US/docs/Web/HTML/Using_the_application_cache

如果还使用301永久重定向,则默认情况下浏览器很可能不会缓存重定向并加载https,请参阅:https://en.wikipedia.org/wiki/HTTP_301

希望这足以满足您的需求,如果不是,我想讨论您使用此解决方案所面临的问题。

答案 1 :(得分:2)

I don't think this problem can be solved via a service worker because there is no way to intercept requests to the http scheme. However, it looks like the Strict-Transport-Security header could work.

If provided on a https response, it forces the browser to always use the https scheme to load the page--which should hit the service worker, if it's been correctly installed. This applies both in the case where the user does not type in a scheme (e.g. example.com) or they type in the http scheme (e.g. http://example.com).

答案 2 :(得分:1)

如果由于您的服务设置而无法返回HTTP 301响应或包含Strict-Transport-Security标头等服务器端解决方案,则另一个选项是使用客户端JavaScript更新{{1这将触发页面重新加载。

您可以按照<platinum-https-redirect> Polymer element中使用的技术进行操作,该技术改编如下:

window.location.href