Detect the Internet connection is offline?

后端 未结 19 1782
甜味超标
甜味超标 2020-11-22 00:53

How to detect the Internet connection is offline in JavaScript?

19条回答
  •  轮回少年
    2020-11-22 01:42

    There are a number of ways to do this:

    • AJAX request to your own website. If that request fails, there's a good chance it's the connection at fault. The JQuery documentation has a section on handling failed AJAX requests. Beware of the Same Origin Policy when doing this, which may stop you from accessing sites outside your domain.
    • You could put an onerror in an img, like .

    This method could also fail if the source image is moved / renamed, and would generally be an inferior choice to the ajax option.

    So there are several different ways to try and detect this, none perfect, but in the absence of the ability to jump out of the browser sandbox and access the user's net connection status directly, they seem to be the best options.

提交回复
热议问题