渐进式 Web 应用程序:如何检测和处理连接再次建立时 [英] Progressive Web App: How to detect and handle when connection is up again
本文介绍了渐进式 Web 应用程序:如何检测和处理连接再次建立时的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
使用 PWA,我们可以在离线模式下处理设备连接断开的情况.但是我们如何检测固定网络连接并自动重新加载/重新激活应用程序?
With a PWA, we can handle when the device connection is down with offline mode. But how do we detect a fixed network connection and automatically reload/re-activate the application?
推荐答案
您可以监控 offline
和 online
事件,它们是广泛的支持.此外,您可以通过尝试从目标服务器 URL 获取 HEAD
来测试连接性:
You could monitor the offline
and online
events, which are widely supported. Further, you could test connectivity by attempting to fetch HEAD
from the target server URL:
// 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;
}
<fieldset>
<label>
<span>Server URL for connectivity test:</span>
<input id="serverUrl" style="width: 100%">
</label>
</fieldset>
<script>document.getElementById('serverUrl').value = window.location.origin;</script>
<p>
<i>Use Network Panel in DevTools to toggle Offline status</i>
</p>
处理此问题的一种技术:
线下活动
- 显示离线图标/状态
- 仅启用离线可用的功能(通过缓存数据)
线上活动
- 显示在线图标/状态
- 启用所有功能
这篇关于渐进式 Web 应用程序:如何检测和处理连接再次建立时的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文