← 中文资源

简体中文版本

navigator.onLine 与连接事件

navigator.onLine 提供同步的连接快照,online/offline 事件才是变化信号:断网时暂停队列并展示横幅,恢复时继续未完成的工作。

阅读英文原文

实现说明

navigator.onLine 与连接事件以函数 report、watchConnection为骨架。

使用要点

  • window、navigator 只存在于浏览器——Node 运行时没有现成的垫片。
  • 跑完文件,输出里会留下标记——reconnected — resuming queue、connection lost — pausing。

常见问题

「navigator.onLine 与连接事件」能在裸 Node.js 里跑吗?

不能——window 的家在浏览器里,Node 进程提供不了。执行时请用页面(或 DevTools 控制台)。

主要签名是 const report = ()

核心语句

window.addEventListener('offline', () => {
  // pause polling, show an offline banner, flush state to storage
  console.log('connection lost — pausing');
  report();
});
window.addEventListener('online', () => {
  // browsers differ on what "online" means: here, retry queued work
  console.log('reconnected — resuming queue');
  report();
});
const report = () => {
  console.log(navigator.onLine ? 'connection: online' : 'connection: offline');
};

代码示例

// navigator.onLine is a synchronous snapshot; the online/offline events
// are what tell you it changed
function watchConnection() {
  const report = () => {
    console.log(navigator.onLine ? 'connection: online' : 'connection: offline');
  };

  report();

  window.addEventListener('online', () => {
    // browsers differ on what "online" means: here, retry queued work
    console.log('reconnected — resuming queue');
    report();
  });

  window.addEventListener('offline', () => {
    // pause polling, show an offline banner, flush state to storage
    console.log('connection lost — pausing');
    report();
  });
}

watchConnection();