javascript - 网络连接更改的事件监听器

标签 javascript google-chrome webrtc navigator stun

在 JavaScript(在 Chrome 上)中,每当用户从一个 WiFi 网络切换到另一个 WiFi 网络时,我都会尝试执行一些任务(假设两个网络在性能方面完全相同)。

我开始查看 Window 界面和 navigator.onLineonline/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/

相关文章:

google-chrome - 什么是 manifest.json 文件,我在哪里可以在我的机器上找到它?

javascript - 不向从 javascript Date 创建的对象添加分钟的时刻

javascript - jEditable - 提交表单

html - 打印媒体查询在 Chrome 中被忽略?

css - Chrome 中的 float 右输入

c# - C# 中的简单 Webrtc 中继桥服务器

ionic-framework - 有谁知道如何将 sip.js 版本 0.8 或更高版本与 Electron (桌面应用程序)或 ionic (移动应用程序)一起使用?

javascript - Websockets 比 WebRTC 更快?

javascript - 计算对象值的出现次数

javascript - 尝试使用 jquery 工具将鼠标悬停在覆盖层上