Home > Web Front-end > JS Tutorial > How to detect offline/online status with JavaScript

How to detect offline/online status with JavaScript

coldplay.xixi
Release: 2020-07-08 16:49:07
forward
3006 people have browsed it

How to detect offline/online status with JavaScript

Offline browsing technology has become more and more popular in the past two years. The most common one is HTML5 mobile applications. Many ordinary Web apps also use these technologies. However, the emergence of new technologies sometimes brings additional troubles to us WEB developers. For example, how to determine whether the user is online or offline? Fortunately, where there is a spear, there is a shield. The navigator object in JavaScript helps us solve this problem.

Related learning recommendations: javascript video tutorial

navigator.onLine

navigator.onLineProperties It can provide us with a Boolean value to determine whether the user is connected to the Internet. You can access it like this:

if(navigator.onLine) { // true|false
	// ...
}
Copy after login

It doesn’t get easier than this!

Events

In addition to detecting this offline/online attribute value, we can also bind offline and online events:

function updateIndicator() {
	// 这时可以根据offline/online按钮的颜色
}

// 根据网络连接情况更新在线状态
window.addEventListener('online',  updateIndicator);
window.addEventListener('offline', updateIndicator);
updateIndicator();
Copy after login

Of course, old-fashioned techniques also provide corresponding methods, using the ononline and onoffline methods on the body tag.

I can imagine many places where these events and properties need to be used. For example, when the user is working and the network is disconnected, if our WEB application can detect this state, the user's writing can be saved in the local Web Storage, and then submitted to the server after the network is restored. , In this way, disconnection will not affect the user's writing. This is just a simple example, I believe you can come up with more.

It should be reminded that this API is not so reliable. The oldest scheduled refresh technology can be used as a record.

The above is the detailed content of How to detect offline/online status with JavaScript. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
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 Issues
What is JavaScript garbage collection?
From 1970-01-01 08:00:00
0
0
0
What are JavaScript hook functions?
From 1970-01-01 08:00:00
0
0
0
c++ calls javascript
From 1970-01-01 08:00:00
0
0
0
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template