Offline browsing is becoming increasingly common in HTML5 mobile apps or Web apps, so it's common to use JavaScript to detect browser online/offline status.
navigator.onLine
Properties provide a Boolean value regardless of whether the browser is online or not. If the browser is online, set to true
, otherwise set false
to .
if // True|false // ... }
Online and offline Events:
Browsers also support online
and offline
events when the browser is offline or online.
Window.addeventlistener (' online ', function (e) {console.log (' online ')}); Window.addeventlistener (' Offline ', Function (e) {console.log (' Offline ');});
You can register events in several familiar ways:
- On
window
, document
, or document.body
on the use ofaddEventListener
document
sets the document.body
or ononline
onoffline
property to a JavaScript Function object. (Note: cannot be used or for compatibility window.ononline
reasons window.onoffline
.) )
body
Specify Ononline= "..." on the label in the HTML tag Or onoffline= "..." Characteristics.
Precautions:
- IE8 need to bind events to document.body instead of window
- Online offline change refers to the physical network link changes , if the console is limited to offline the network will not trigger the corresponding event.
Instance code:
<! DOCTYPE html>"en">"UTF-8"> <title> detect Browser Online/offline status with JavaScript (JavaScript API?—? navigator.online) </title> <style type="Text/css">#status {position:fixed; Width: -%; Font:bold 1em sans-serif; Color: #FFF; padding:0. 5em; } #log {padding:2.5em0.5em0. 5em; Font:1em sans-serif; }. online {background:green; }. offline {background:red; } </style>"Status"></div><div id="Log"></div><button type="Button"Id="Test"> Check Status </button><script>Window.addeventlistener ('Load', function () {varTESTBTN = document.getElementById ("Test"); varStatus = document.getElementById ("Status"); varLog = document.getElementById ("Log"); function Updateonlinestatus (Event) { varCondition = Navigator.online?"Online":"Offline"; Status.classname=condition; Status.innerhtml=condition.touppercase (); Log.insertadjacenthtml ("BeforeEnd","Event:"+ (Event?Event. Type:"-") +"; Status:"+ condition+" | "); } window.addeventlistener ('Online', Updateonlinestatus); Window.addeventlistener ('Offline', Updateonlinestatus); Testbtn.addeventlistener ("Click", Updateonlinestatus); Updateonlinestatus ();});</script></body>
Detect browser online/offline status with JavaScript (JavaScript API?—? navigator.online)