Last active
October 7, 2016 16:23
-
-
Save khalidsalomao/81aa293b6b6ac7a9d8679b8991c2ee41 to your computer and use it in GitHub Desktop.
Detect internet active connection: influenced by https://gist.github.com/jpsilvashy/5725579, https://github.com/HubSpot/offline/blob/master/js/offline.js
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function checkConnection(callback, timeout) { | |
var checkStatus = function() { | |
report((xhr.status && xhr.status < 12000) ? 'up' : 'down'); | |
}; | |
var last = ''; | |
var report = function(status){ | |
if (status !== last){ | |
last = status; | |
callback(status === 'up'); | |
} | |
}; | |
var url = "//" + window.location.hostname + "/?_=" + (new Date()).getTime(); | |
var xhr = new XMLHttpRequest(); | |
xhr.timeout = timeout || 2000; | |
if (xhr.onprogress === null) { | |
xhr.onload = checkStatus; | |
xhr.onerror = checkStatus; | |
xhr.ontimeout = checkStatus; | |
} else { | |
xhr.onreadystatechange = function() { | |
if (xhr.readyState === 4) { | |
checkStatus(); | |
} else if (xhr.readyState === 0) { | |
report('down'); | |
} | |
}; | |
} | |
try { | |
xhr.open("HEAD", url); | |
xhr.send(); | |
} catch (error) { | |
report('down'); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment