Home>Article>Web Front-end> How javascript detects the network

How javascript detects the network

藏色散人
藏色散人 Original
2021-05-19 11:05:25 8456browse

Javascript method to detect the network: 1. Detect the network through navigator; 2. Use "window.ononline" and "window.onoffline" events to monitor the browser's networking status; 3. Detect the network through ajax request.

How javascript detects the network

The operating environment of this article: windows7 system, javascript version 1.8.5, DELL G3 computer

JavaScript determines the network status

1. Generally speaking, to judge the network status, the navigator provided by HTML5 is used to detect the network

How javascript detects the network

2. If you want to monitor the browser’s networking status, use window.ononline and window.onoffline events:

or:

How javascript detects the network
Note: This method belongs to the "listener" and will only be triggered the moment the network is connected/disconnected.

Summary:navigator.onLineandonline,offlineevents are not omnipotent. On the PC side, only It can determine whether the wireless and network cables are connected, but it cannot determine whether there is a network or whether the Internet can be accessed.

A safer approach:

Note that to detect the ononline event, it must be bound to the window object

attachEvent - compatible with: IE7, IE8; not compatible with firefox, chrome, IE9, IE10, IE11, safari, opera
addEventListener - compatible with: firefox, chrome, IE, safari, opera; not compatible with IE7, IE8

Recommended study: "javascript Advanced Tutorial"

3. You can initiate an ajax request and determine the network connectivity based on the request result

Of course, this method is not perfect, and it is not very practical. It cannot well distinguish whether the server is faulty or the user's network has problems, but this is indeed the most effective way.

The above is the detailed content of How javascript detects the network. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn