Sunday 24 July 2022

Event listener for network connection change

In JavaScript (on Chrome) I am trying to perform some task whenever a user switches from one WiFi network to another (assuming that both networks are exactly the same in terms of performance).

I started with looking at the online / offline events of the Window interface and navigator.onLine but it seems like that they are not triggered when we switch networks (disconnect from one network and connect to the other) because

In Chrome and Safari, if the browser is not able to connect to a local area network (LAN) or a router, it is offline; all other conditions return true.

you cannot assume that a true value necessarily means that the browser can access the internet. You could be getting false positives, such as in cases where the computer is running a virtualization software that has virtual ethernet adapters that are always "connected."

Ref1: https://developer.mozilla.org/en-US/docs/Web/API/Navigator/onLine

Ref2: why navigator.onLine() return true even if my internet connection is not working?

Also, the navigator.connection object not necessarily updates to trigger navigator.connection.onchange event in case of switching networks.

I tried using WebRTC with STUN to capture public IP address to differentiate between the two connections but there is no event listener that would reliably tell that a network change has happened.

I understand that JavaScript can not directly access network info through the browser due to security reasons but is there an alternative that can be reliably used to trigger an event whenever the network is switched or there is no actual internet connectivity even though the computer is connected to the LAN/WiFi?



from Event listener for network connection change

No comments:

Post a Comment