niv*_*ved 3 javascript google-chrome-devtools service-worker progressive-web-apps
我一直在关注本教程https://codelabs.developers.google.com/codelabs/offline/#7
到目前为止,我能够让我的服务工作人员缓存脱机页面并加载它,但我只想在没有互联网访问时显示此offline.html 页面。现在它的工作方式是,每次我刷新页面时,即使可以访问互联网,它也会显示它,除非我选中Bypass for network开发人员工具中 Chrome 的“应用程序”选项卡中的复选框。
self.addEventListener('fetch', function(event) {
console.log(event.request.url);
event.respondWith(
fetch('https://mysite/offline.html')
);;
});
Run Code Online (Sandbox Code Playgroud)
您可以利用navigator.onLine. 它返回true在线和false其他方式。
window.addEventListener('DOMContentLoaded', function() {
var status = document.getElementById("status");
function updateOnlineStatus(event) {
var condition = navigator.onLine ? "online" : "offline";
status.className = condition;
status.innerHTML = condition.toUpperCase();
}
window.addEventListener('online', updateOnlineStatus);
window.addEventListener('offline', updateOnlineStatus);
});Run Code Online (Sandbox Code Playgroud)
#status {
width: 100%;
font: bold 1em sans-serif;
color: #FFF;
padding: 0.5em;
}
.online {
background: green;
}
.offline {
background: red;
}Run Code Online (Sandbox Code Playgroud)
<div id="status" class="online"> ONLINE </div>
<p> Toggle your network connection to see the effect </p>Run Code Online (Sandbox Code Playgroud)