在 JavaScript(在 Chrome 上)中,每当用户从一个 WiFi 网络切换到另一个 WiFi 网络时,我都会尝试执行一些任务(假设两个网络在性能方面完全相同)。
我开始查看 Window 界面和 navigator.onLine
的 online
/offline
事件,但似乎它们不是当我们切换网络(从一个网络断开连接并连接到另一个网络)时触发,因为
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."
引用号1:https://developer.mozilla.org/en-US/docs/Web/API/Navigator/onLine
引用号2:why navigator.onLine() return true even if my internet connection is not working?
此外,在切换网络的情况下,navigator.connection
对象不一定会更新以触发 navigator.connection.onchange
事件。
我尝试使用 WebRTC 和 STUN 来捕获公共(public) IP 地址以区分两个连接,但没有事件监听器可以可靠地告知网络已发生更改。
我知道,由于安全原因,JavaScript 无法通过浏览器直接访问网络信息,但是有没有一种替代方案可以可靠地用于在网络切换时触发事件,或者即使计算机没有实际的互联网连接是否已连接到 LAN/WiFi?
最佳答案
您正在寻找的内容没有广泛的浏览器支持,但确实存在于基于 Chromium 的浏览器中:https://developer.mozilla.org/en-US/docs/Web/API/NetworkInformation/change_event
关于javascript - 网络连接更改的事件监听器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/73026775/