Home>Article>Web Front-end> How javascript detects the network
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.
The operating environment of this article: windows7 system, javascript version 1.8.5, DELL G3 computer
JavaScript determines the network status
or:
Note: This method belongs to the "listener" and will only be triggered the moment the network is connected/disconnected.
Summary:navigator.onLine
andonline
,offline
events 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"
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!