【问题标题】:How to check online status in React.js?如何在 React.js 中查看在线状态?
【发布时间】:2022-01-11 03:12:40
【问题描述】:

我创建了一个函数来检查应用程序是否在线。但是,根据 MDN 文档,navigator.onLine 在 Chrome 和 Safari 上给出了误报,这是我目前正在经历的。有没有其他方法可以解决当前的问题?

useOnlineStatus.ts:

import { useEffect, useState } from 'react'

const getOnlineStatus = (): boolean => {
  return typeof navigator !== 'undefined' &&
    typeof navigator.onLine === 'boolean'
    ? navigator.onLine
    : true
}

const useOnlineStatus = (): boolean => {
  const [onlineStatus, setOnlineStatus] = useState(getOnlineStatus())

  const goOnline = () => setOnlineStatus(true)

  const goOffline = () => setOnlineStatus(false)

  useEffect(() => {
    window.addEventListener('online', goOnline)
    window.addEventListener('offline', goOffline)

    return () => {
      window.removeEventListener('online', goOnline)
      window.removeEventListener('offline', goOffline)
    }
  }, [])

  return onlineStatus
}

export default useOnlineStatus

【问题讨论】:

  • 你的测试怎么样?
  • 我尝试断开 WiFi 或任何 LAN 连接,并将网络节流配置文件从“无节流”更改为“离线”
  • 更改网络节流配置文件有效,但在断开 WiFi 或任何 LAN 连接时无效。

标签: javascript reactjs internet-connection network-connection


【解决方案1】:

您可以尝试的一种方法是向您自己的来源发送请求,以检查您的应用程序是否在线。

查询参数 (q) 是随机的,以避免缓存响应。

const isAppOnline = async() => {
  if (!window.navigator.onLine) return false

  const url = new URL(window.location.origin)
  url.searchParams.set('q', new Date().toString())

  try {
    const response = await fetch(
      url.toString(),
      { method: 'HEAD' },
    )

    return response.ok
  } catch {
    return false
  }
}

【讨论】:

    猜你喜欢
    • 2023-03-15
    • 1970-01-01
    • 2017-04-28
    • 1970-01-01
    • 2011-05-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多