gpt4 book ai didi

javascript - 渐进式 Web 应用程序 : How to detect and handle when connection is up again

转载 作者:可可西里 更新时间:2023-11-01 02:28:32 25 4
gpt4 key购买 nike

使用 PWA,我们可以在离线模式下处理设备连接断开的情况。但是我们如何检测固定网络连接并自动重新加载/重新激活应用程序?

最佳答案

您可以监控 offline and online events , 这是 widely supported .此外,您可以通过尝试从目标服务器 URL 获取 HEAD 来测试连接性:

// 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>

一个technique处理这个:

  • 线下事件

    • 显示离线图标/状态
    • 仅启用离线可用的功能(通过缓存数据)
  • 在线事件

    • 显示在线图标/状态
    • 启用所有功能

关于javascript - 渐进式 Web 应用程序 : How to detect and handle when connection is up again,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44756154/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com