你如何检查在渐进式网络应用中是否在线?

huangapple go评论82阅读模式
英文:

How can you check if you are online in a Progressive Web Application

问题

我正在开发一个渐进式Web应用程序,并尝试确保最终用户可以在离线状态下本地访问和编辑他们的信息,然后在重新联机后与数据库同步。我知道这是可能的,但我似乎找不到指导我如何做到这一点的资源。

我想检查用户是否在线:

  • 是的,然后使用我的API对其进行身份验证/授权以访问应用程序内容
  • 不是的,然后设置一个免责声明,如果他们以前没有在在线状态下登录到此设备并选择记住他们,那么他们将无法访问应用程序内容。但如果他们曾经这样做过,他们可以登录。

只是检查他们是否在线是我目前遇到困难的部分。

我尝试使用ping来检测,但浏览器不支持ping。
我还尝试使用如下链接中所示的navigator.onLine:
https://developer.mozilla.org/en-US/docs/Web/API/Navigator/onLine#basic_usage

我考虑过查看等待方法是否超时,但我还是很新手,找不到任何解释是否可以这样做以及如何做的信息。

对此的任何帮助将不胜感激。

英文:

I am developing a Progressive Web Application and I am trying to make sure that end users can access and edit their information locally while offline and then sync it with the database once coming back online. I know its possible I just cannot seem to find the resources that point me to how to do this.
I want to check to see if the user is online
-> yes then use my api to authenticate/authorize them to access application content
-> no then set a disclaimer that if they have not logged into this device previously while online and selected for the device to remember them then they will not be able to access the application content. But if they have then they can log in.

Just checking if they are online is the part that I am struggling with at the moment.

I have tried using a ping to discover that browsers do not support a ping.
I also tried using the navigator.onLine as shown in the link below:
https://developer.mozilla.org/en-US/docs/Web/API/Navigator/onLine#basic_usage

I thought about looking into if a await method times out, but I am still pretty new, and I couldn't find anything that explained if I could do that and how.

Any help with this would be greatly appreciated.

答案1

得分: 1

你可以使用以下3种方法:

console.log(navigator.onLine); // 返回一个布尔值

// 当互联网连接时触发此事件:
window.addEventListener('online', () => {
console.log('已连接至互联网...');
})

// 当互联网断开连接时触发此事件:
window.addEventListener('offline', () => {
console.log('已断开互联网连接...');
})

英文:

You can use thease 3 methods:

console.log(navigator.onLine); // Returns a Boolean  


// This event is called when the internet is connected:

window.addEventListener('online', ()=>{
  console.log('onlined...');
})


// This event is called when the internet is disconnected:

window.addEventListener('offline', ()=>{
  console.log('offlined...');
})

huangapple
  • 本文由 发表于 2023年7月27日 22:15:03
  • 转载请务必保留本文链接:https://go.coder-hub.com/76780637.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定