You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何强制将window.navigator.onLine始终设置为true?

解决方案:强制window.navigator.onLine始终返回true

要绕过window.navigator的只读限制,实现强制返回true的需求,你可以通过重定义window.navigator的getter,让它返回一个包装了原navigator的Proxy对象,拦截onLine属性的读取逻辑。

为什么直接用Proxy赋值会报错?

window.navigator本身是一个仅包含getter的属性,直接执行window.navigator = new Proxy(...)会触发set操作,但该属性没有对应的setter,因此会抛出Cannot set property navigator of #<Window> which has only a getter错误。必须通过Object.defineProperty修改它的getter逻辑,才能替换返回的对象。

可行代码示例

// 保存原始的navigator对象,避免丢失原有功能
const originalNavigator = window.navigator;

// 创建Proxy拦截onLine属性的读取
const modifiedNavigator = new Proxy(originalNavigator, {
  get(target, prop) {
    // 拦截onLine属性,强制返回true
    if (prop === 'onLine') {
      return true;
    }
    // 其他属性和方法保持原navigator的行为
    return Reflect.get(target, prop);
  }
});

// 重写window.navigator的getter,返回我们的Proxy对象
Object.defineProperty(window, 'navigator', {
  get() {
    return modifiedNavigator;
  },
  configurable: true, // 允许后续重新配置(可选)
});

备选方案(直接重写onLine属性)

如果你的目标浏览器允许直接修改navigator.onLine的getter,可以用更简洁的方式:

Object.defineProperty(window.navigator, 'onLine', {
  get() {
    return true;
  },
  configurable: true,
});

注意:这种方式在部分浏览器(如Chrome)中可能因navigator属性被锁定而失效,因此Proxy方案的兼容性和可靠性更高。

验证效果

执行上述代码后,在控制台输入window.navigator.onLine,会始终返回true,所有依赖库读取该属性时都会拿到预期值,无需修改依赖代码。

内容的提问来源于stack exchange,提问作者nh2

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.24 07:52:20