How javascript detects the network

藏色散人
Release: 2023-01-06 11:14:10
Original
8402 people have browsed it

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

Copy after login

How javascript detects the network

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

Copy after login

or:

Copy after login

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:

Copy after login

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

Copy after login

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!

Related labels:
source:php.cn
Statement of this Website
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
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!