cordova-plugin-network-information连VPN时onDisconnect()不触发的解决办法
解决cordova-plugin-network-information在VPN连接下关闭WiFi不触发onDisconnect的问题
cordova-plugin-network-information的onDisconnect事件依赖系统网络状态广播,当VPN处于连接状态时,即使关闭WiFi,系统可能仍认为VPN接口是活跃的,因此不会触发断开事件。以下是几个可行的解决方案:
方案1:主动轮询网络状态
通过定期主动获取当前网络类型,对比状态变化来触发离线/在线逻辑,作为事件监听的兜底方案:
import { Network } from '@ionic-native/network/ngx'; import { interval } from 'rxjs'; private currentIsOnline = true; constructor(private network: Network) { // 每2秒轮询一次网络状态 interval(2000).subscribe(() => { const newStatus = this.network.type !== 'none'; if (!newStatus && this.currentIsOnline) { this.triggerOffline(); this.currentIsOnline = false; } else if (newStatus && !this.currentIsOnline) { setTimeout(() => this.triggerOnline(), 1000); this.currentIsOnline = true; } }); // 保留原有事件监听作为补充 this.network.onDisconnect().subscribe(() => this.triggerOffline()); this.network.onConnect().subscribe(() => setTimeout(() => this.triggerOnline(), 1000)); } private triggerOffline() { this.genericService.setNetworkStatusFlag(false); this.toast.presentFailureToast('You are offline.Please try later'); } private triggerOnline() { this.genericService.setNetworkStatusFlag(true); }
方案2:结合VPN状态判断
通过检测VPN是否激活,再结合网络类型判断实际连通性:
可以使用现成的Cordova插件(如cordova-plugin-vpn-check)来检测VPN状态,示例代码如下:
import { Network } from '@ionic-native/network/ngx'; import { VpnCheck } from '@ionic-native/vpn-check/ngx'; constructor(private network: Network, private vpnCheck: VpnCheck) { this.network.onDisconnect().subscribe(async () => { const isVpnActive = await this.vpnCheck.isVpnEnabled(); // 如果VPN激活但网络类型为none(WiFi已关),强制触发离线逻辑 if (isVpnActive && this.network.type === 'none') { this.triggerOffline(); } }); // 同样搭配轮询逻辑确保可靠性 interval(2000).subscribe(async () => { const isVpnActive = await this.vpnCheck.isVpnEnabled(); const hasNetwork = this.network.type !== 'none'; if (isVpnActive && !hasNetwork && this.currentIsOnline) { this.triggerOffline(); this.currentIsOnline = false; } }); }
方案3:检测实际网络连通性
直接通过ping操作验证是否真的能联网,避免依赖系统网络状态标记:
可以使用cordova-plugin-ping插件实现ping功能,示例代码:
import { Network } from '@ionic-native/network/ngx'; import { Ping } from '@ionic-native/ping/ngx'; import { interval } from 'rxjs'; private currentIsOnline = true; constructor(private network: Network, private ping: Ping) { interval(3000).subscribe(async () => { try { // 尝试ping公共DNS服务器,超时1秒 const result = await this.ping.ping('8.8.8.8', 1); const newStatus = result.success; if (!newStatus && this.currentIsOnline) { this.triggerOffline(); this.currentIsOnline = false; } else if (newStatus && !this.currentIsOnline) { this.triggerOnline(); this.currentIsOnline = true; } } catch (err) { if (this.currentIsOnline) { this.triggerOffline(); this.currentIsOnline = false; } } }); }
以上方案可以单独使用或组合使用,优先推荐方案1+方案3的组合,既保证性能又能准确判断实际网络状态。
内容的提问来源于stack exchange,提问作者VARSHA S
相关产品推荐
相关产品推荐

