简体   繁体   English

使用 service worker 检测离线或在线

[英]detect offline or online using service worker

I am using service worker to check if a user is online or offline when a request is made.我正在使用服务工作者来检查用户在发出请求时是在线还是离线。 Here are some of the approaches I have taken:以下是我采取的一些方法:

  1. In this method in service worker,在服务工作者的这个方法中,
self.addEventListener("fetch", (event) => {
    if (navigator.onLine){

    }
})

navigator.onLine only works when you check/uncheck the offline checkbox in Inspect Element. navigator.onLine仅在您选中/取消选中 Inspect Element 中的离线复选框时才有效。 But when I switch the device's internet on/off, it will always return true whether im offline or online.但是当我打开/关闭设备的互联网时,无论我离线还是在线,它都会返回 true。 And also from what i've seen in other answers, navigator.onLine will return true if you are connected to your local network even if your local network has no internet connection.而且从我在其他答案中看到的内容来看,如果您连接到本地网络,即使您的本地网络没有互联网连接, navigator.onLine也会返回 true。

  1. I have tried to ping a url in the self.addEventListener("fetch", {...}) method as shown here https://stackoverflow.com/a/24378589/6756827 .我试图在self.addEventListener("fetch", {...})方法中 ping url ,如此处所示https://stackoverflow.com/a/24378589/6756827 This will bring an error in in the new XMLHttpRequest();这将在new XMLHttpRequest();中带来错误。 object. object。

  2. I have tried to load an online resource (an image) in the self.addEventListener("fetch", {...}) method as shown here https://stackoverflow.com/a/29823818/6756827 .我试图在self.addEventListener("fetch", {...})方法中加载在线资源(图像),如此处所示https://stackoverflow.com/a/29823818/6756827 The console shows an error for new Image();控制台显示new Image(); . .

Because none of these approaches work, how do we check if a user is online or offline in service worker when a request is made?由于这些方法都不起作用,我们如何在发出请求时检查用户在 service worker 中是在线还是离线?

In the service worker you do not have access to the navigator object and thus no access to the online property or events.在服务人员中,您无权访问导航器 object,因此无法访问在线属性或事件。

Instead you know you are offline when a fetch throws an exception.相反,当 fetch 引发异常时,您知道自己处于脱机状态。 The only time a fetch will throw an exception is when the device cannot connect to the Internet/Network.只有当设备无法连接到 Internet/网络时,提取会引发异常。

self.addEventListener( "fetch", function ( event ) {

event.respondWith(

    handleRequest( event )
    .catch( err => {
        //assume offline as everything else should be handled
        return caches.match( doc_fallback, {
            ignoreSearch: true
        } );

    } )

);

} ); });

For a more complex handling of the situation you can sync messages of online/offline state with the UI using the message API:对于更复杂的情况处理,您可以使用消息 API 将在线/离线 state 的消息与 UI 同步:

self.addEventListener( "message", event => {
    //handle message here
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM