'Simplest way to determine if the user has internet connection? Navigation.onLine doesn't work since it always returns true on some OS

I am trying to create a function that tells me if the user currently has internet connection. The first thing that came to mind was to use navigation.onLine, however, it turned out that on Windows 11 and Linux with Chrome, it always returns true, so this is unusable.

My second idea is to make a GET request to some resource and assume that the user has no connection if the request fails, but that seems very crude to me.

Do I have any other alternatives?



Solution 1:[1]

You will need to perform a GET request and if that request is successful do something, while if that request times out, do something else.

It is advisable to request to the same domain that's opened or which accepts requests.

EDIT

As @Corey Ogburn pointed out in the comment section, a HEAD request is better in terms of performance than a GET request.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1