题意:怎样使单一 HTML 网页在 Chrome 中离线可用?
问题背景:
I'm hosting a single-HTML web page (all design elements included in the .html file itself) on my webserver, and I'd like to make it available for my users when they are offline. It should work like this: when the user is online, he visits my web page, Chrome saves the .html file locally; when the user is offline and he tries to visit my web page, Chrome is using the local .html file instead. JavaScript must work on the webpage even in offline mode. The user must never see a You are offline error message when visiting my page, and the saved copy of my page mustn't expire from the browser's cache for at least 2 weeks. Everything must work automatically for the user, no need to change Chrome settings and no need to install Chrome extensions. Is this possible?
我在我的网络服务器上托管一个单一的 HTML 网页(所有设计元素都包含在 .html 文件中),我希望在用户离线时也能让他们访问该网页。它应该这样工作:当用户在线时,他访问我的网页,Chrome 将 .html 文件保存在本地;当用户离线并尝试访问我的网页时,Chrome 将使用本地的 .html 文件。即使在离线模式下,网页上的 JavaScript 也必须正常工作。用户在访问我的网页时绝不能看到“您已离线”的错误消息,保存的页面副本必须在浏览器缓存中至少保留 2 周。所有这一切都必须自动为用户工作,无需更改 Chrome 设置,也无需安装 Chrome 扩展程序。这可能吗?
The included JavaScript is smart enough to use window.localStorage
to save data, and sync it with the server as soon as the user is online again.
包含的 JavaScript 足够智能,可以使用 `window.localStorage` 保存数据,并在用户再次在线时立即与服务器同步。
问题解决:
Service workers can use the cache API to download pages; but the cache API doesn't use the user's cookies in Firefox, so what is getting cached can be different from what the user sees.
Service Worker 可以使用缓存 API 下载页面;但在 Firefox 中,缓存 API 不会使用用户的 cookies,因此缓存的内容可能与用户看到的内容不同。
In Firefox, offline mode can be enabled (forced) in File / Work Offline.
在 Firefox 中,可以通过“文件”/“离线工作”来启用(强制)离线模式。
In Chrome, offline mode can be enabled (forced) for the current tab in the developer tools (Ctrl-Shift-J): in the Network tab, enable Offline.
在 Chrome 中,可以在开发者工具(Ctrl-Shift-J)中为当前标签页启用(强制)离线模式:在“网络”标签中,启用“离线”。
In Firefox 55, offline caching seems to work by default (no need for manifest.json
). Chrome needs service workers to make the page available offline.
在 Firefox 55 中,离线缓存似乎默认启用(不需要 manifest.json)。Chrome 需要使用 Service Worker 才能使页面离线可用。
Here is how to detect offline mode in JavaScript:
以下是如何在 JavaScript 中检测离线模式:
<script>document.write('navigator.onLine=' + navigator.onLine);</script>