Created
November 20, 2017 10:57
-
-
Save fijiwebdesign/5150d258d6abb7ce4d855feb2eb31b0b to your computer and use it in GitHub Desktop.
Test if we have an internet connection with JS
This file contains hidden or 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 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