Home >Web Front-end >JS Tutorial >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
<script type="text/javascript"> // 通过window.navigator.onLine 来检测网络是否可用 alert(window.navigator.onLine); // 返回的是一个bool值(true表示已连接,false表示未连接) </script>
<script type="text/javascript"> window.addEventListener("offline",function(){alert("网络连接恢复");}) window.addEventListener("online",function(){alert("网络连接中断");}) </script>
or:
<script type="text/javascript"> window.ononline=function(){alert("网络连接恢复");} window.onoffline=function(){alert("网络连接中断");} </script>
Note: This method belongs to the "listener" and will only be triggered the moment the network is connected/disconnected.
Summary: navigator.onLine
and online
, 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:
<script type="text/javascript"> var el = document.body; if (el.addEventListener) { window.addEventListener("online", function () { alert("网络连接恢复");}, true); window.addEventListener("offline", function () { alert("网络连接中断");}, true); } else if (el.attachEvent) { window.attachEvent("ononline", function () { alert("网络连接恢复");}); window.attachEvent("onoffline", function () { alert("网络连接中断");}); } else { window.ononline = function () { alert("网络连接恢复");}; window.onoffline = function () { alert("网络连接中断");}; } </script>
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"
<script> $.ajax({ url: 'https://sug.so.360.cn/suggest', dataType:'jsonp', success: function(result){ console.log('网络正常') }, error: function(result){ console.log('网络异常') } }); </script>
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!