Detect Online Connection with JavaScript


To check if you are online, query window.navigator.onLine, as in the following example:

if (navigator.onLine) { console.log(online);} else { console.log(offline);}

If the browser doesn't support navigator.onLine the above example will always come out as false/undefined.To see changes in the network state, use addEventListener to listen for the for the events on window.ononline and window.onoffline, as in the following example:

window.addEventListener(offline, function(e) { console.log(offline); });window.addEventListener(online, function(e) { console.log(online); });


window.addEventListener('load', function() { var status = document.getElementById('status'); function updateOnlineStatus(event) { var condition = navigator.onLine ? online : offline; status.className = condition; status.innerHTML = condition.toUpperCase(); log.insertAdjacentHTML('beforeend', 'Event: ' + event.type + '; Status: ' + condition); } window.addEventListener(online, updateOnlineStatus); window.addEventListener(offline, updateOnlineStatus);});
<div id='status'></div><div id='log'></div><p>This is a test</p>