Detect the Internet connection is offline?

后端 未结 19 1937
甜味超标
甜味超标 2020-11-22 00:53

How to detect the Internet connection is offline in JavaScript?

19条回答
  •  夕颜
    夕颜 (楼主)
    2020-11-22 01:48

    window.navigator.onLine
    

    is what you looking for, but few things here to add, first, if it's something on your app which you want to keep checking (like to see if the user suddenly go offline, which correct in this case most of the time, then you need to listen to change also), for that you add event listener to window to detect any change, for checking if the user goes offline, you can do:

    window.addEventListener("offline", 
      ()=> console.log("No Internet")
    );
    

    and for checking if online:

    window.addEventListener("online", 
      ()=> console.log("Connected Internet")
    );
    

提交回复
热议问题