我一直在关注本教程https://codelabs.developers.google.com/codelabs/offline/#7
,到目前为止,我能够使我的服务工作者缓存脱机页面并加载它,但是我只想在没有互联网访问权限时显示此offline.html页面。现在它的工作方式是,即使我没有互联网访问,每次刷新页面都会显示它,除非我在开发人员工具的Chrome的“应用程序”标签中选中了Bypass for network
复选框。
self.addEventListener('fetch', function(event) {
console.log(event.request.url);
event.respondWith(
fetch('https://mysite/offline.html')
);;
});
答案 0 :(得分:2)
您可以使用 navigator.onLine ,它会根据网络连接性返回true或false,您可以看看它Best practices for detecting offline state in a service worker可能会有帮助。
答案 1 :(得分:0)
您可以使用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);
});
#status {
width: 100%;
font: bold 1em sans-serif;
color: #FFF;
padding: 0.5em;
}
.online {
background: green;
}
.offline {
background: red;
}
<div id="status" class="online"> ONLINE </div>
<p> Toggle your network connection to see the effect </p>