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

How to detect offline/online status with JavaScript

coldplay.xixi
coldplay.xixi forward
2020-07-08 16:49:07 2719browse

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. Thenavigatorobject 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 // ... }

It doesn’t get easier than this!

Events

In addition to detecting this offline/online attribute value, we can also bindofflineandonlineevents:

function updateIndicator() { // 这时可以根据offline/online按钮的颜色 } // 根据网络连接情况更新在线状态 window.addEventListener('online', updateIndicator); window.addEventListener('offline', updateIndicator); updateIndicator();

Of course, old-fashioned techniques also provide corresponding methods, using theononlineandonofflinemethods on thebodytag.

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!

Statement:
This article is reproduced at:webhek.com. If there is any infringement, please contact admin@php.cn delete