Skip to content

Instantly share code, notes, and snippets.

@fijiwebdesign
Created November 20, 2017 10:57
Show Gist options
  • Save fijiwebdesign/5150d258d6abb7ce4d855feb2eb31b0b to your computer and use it in GitHub Desktop.
Save fijiwebdesign/5150d258d6abb7ce4d855feb2eb31b0b to your computer and use it in GitHub Desktop.
Test if we have an internet connection with JS
function testConnection() {
var url = location.href.match(/^https?\:/i) ? '/' : 'https://google.com'
var rand = parseInt(Math.ceil(Math.random()*Math.pow(10, 14))).toString(16)
var retry = ms => setTimeout(() => testConnection(), ms || 5000)
var notify = msg => document.body.innerHTML = `<h1 style="font-size:300%;position:fixed;top:40%;width:100%;text-align:center;">${msg}</h1>`
var handleResp = (err, msg) => {
console.log(err, new Date, msg)
notify(msg)
retry()
}
fetch(url + '?' + rand, {mode: 'no-cors'} )
.then( () => handleResp(null, 'Connected!') )
.catch( e => handleResp(e, 'Disconnected! Retry...') )
}
testConnection()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment