I referred to this Detect the Internet connection is offline? question to find out how to check if the browser is offline or online.
So I used window.navigator.onLine to find that out.
The problem is that, no matter what I do, window.navigator.onLine is always true.
I am using brave browser, but I’m not sure if that’s related to the issue, it’s chromium based.
I’m on Ubuntu Linux, desktop.
I just want to detect when the browser becomes offline to show a small message "connection lost".
In react the code looks as follows:
const online = window.navigator.onLine
useEffect(() => {
if (online) return
console.log("Connection lost!")
}, [online])
try to toggle your wifi on and on to see the console logs
Here’s a stack blitz instance to try it out, it’s a pretty small code, (Click me)
2
Answers
https://developer.mozilla.org/en-US/docs/Web/API/Navigator/onLine
So the value won’t update unless you make a request of some sort.
There are also some implementation specific notes on the same url.
In other words, if there is any sort of network access it will be
true
, even if you are not connected to the internet.So the best way to check this is probably to just make a request to an API endpoint or other resource that is only available while online and base your status on if the request was successful or not. Since in most cases just being "online" isn’t worth much if your API is inaccessible this would probably provide better information to your users as well.
Need to use the event listener for this:
window.addEventListener('online', () => { ...});
.Inside the callback for listener, do
setState
to check online off-line toggle.here is small
hook
i created inreactjs
to handle online offline states: