Han*_*ung 10 javascript offlineapps progressive-web-apps
使用PWA,现在我们可以在离线模式下关闭设备连接.但问题是当用户修复他们的连接时,我们如何检测它并自动重新加载/重新激活应用程序,以便用户不必自己动手?
ton*_*y19 32
你可以监视 offline和online事件,这是广泛的支持:
// Test this by running the code snippet below and then
// use the "Offline" checkbox in DevTools Network panel
window.addEventListener('online', handleConnection);
window.addEventListener('offline', handleConnection);
function handleConnection() {
if (navigator.onLine) {
isReachable(getServerUrl()).then(function(online) {
if (online) {
// handle online status
console.log('online');
} else {
console.log('no connectivity');
}
});
} else {
// handle offline status
console.log('offline');
}
}
function isReachable(url) {
/**
* Note: fetch() still "succeeds" for 404s on subdirectories,
* which is ok when only testing for domain reachability.
*
* Example:
* https://google.com/noexist does not throw
* https://noexist.com/noexist does throw
*/
return fetch(url, { method: 'HEAD', mode: 'no-cors' })
.then(function(resp) {
return resp && (resp.ok || resp.type === 'opaque');
})
.catch(function(err) {
console.warn('[conn test failure]:', err);
});
}
function getServerUrl() {
return document.getElementById('serverUrl').value || window.location.origin;
}Run Code Online (Sandbox Code Playgroud)
处理这个的一种技术:
离线活动
在线活动
Nic*_*zey 17
小心online事件,只告诉设备是否连接.它可以连接到WiFi热点而无需实际的Internet连接(例如,因为凭据).
| 归档时间: |
|
| 查看次数: |
10221 次 |
| 最近记录: |