Home > OS >  Event listener for network connection change
Event listener for network connection change

Time:07-20

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?

CodePudding user response:

What you are looking for does not have wide browser support, but does exist in Chromium-based browsers: https://developer.mozilla.org/en-US/docs/Web/API/NetworkInformation/change_event

CodePudding user response:

This is known as "walk out of the door" problem. These slides from a 2015 IETF meeting explain it well: https://www.ietf.org/proceedings/94/slides/slides-94-ice-6.pdf

In a nutshell what you need to do in the browser is to wait for the old connection to get disconnected and initiate an ICE restart to reestablish the connection.

  • Related