SoFunction
Updated on 2025-04-10

Several ways to use JS to determine the current network connection status in a browser

Several methods to use JS to determine the current network status in the browser are as follows:

1.

2. ajax request

3. Obtain network resources

4. bind()

1.

By determining the current network status:

if(){
 ...
}else{
 ...
}

Very simple, but not accurate - according to MDN's description:

It will only return false if the machine is not connected to the LAN or router, and in other cases true.

In other words, after the machine is connected to the router, even if the router does not connect to the network, it still returns true.

2. ajax request

Use the get request method to determine whether the data can be successfully obtained based on the return value, thereby determining the current network status:

$.ajax({
 url: '',
 success: function(result){
  ...
 }, 
 error: function(result){
  ...
 }
});

3. Obtain network resources

The principle is the same as 2. Put a hidden image on the page and set its onerror function (this function will be called when the image resource is failed):

<script src="./jquery-3.1."></script>
<script>
function getImgError(){
 alert("Network disconnect!");
}
$().ready(function(){
 $("#btn-test").click(function(){
  var imgPath = "/img/bd_logo1.png";
  var timeStamp = (new Date());
  $("#img-test").attr("src", imgPath + "?timestamp=" + timeStamp);
 });
});
</script>
<body>
 <img  style="display:none;" onerror="getImgError()"/>
 <button >check status</button>
</body>

Each time button is clicked, the src of the image is updated. If the image is failed, the network connection is considered to be failed.

The accuracy of this judgment of network status depends entirely on whether the image resources are stable. . .

4. bind()

The principle is the same as 1:

var netStatue = true;
$(window).bind('online', function(){
 netStatue = true;
});
$(window).bind('offline', function(){
 netStatue = false;
});
...
if(netStatue){
 ...
}else{
 ...
}

The above is all the content of this article. I hope it will be helpful to everyone's study and I hope everyone will support me more.