Reputation:
I am trying to check internet connection in js:
function doesConnectionExist() {
var xhr = new XMLHttpRequest();
var file = "https://www.google.com";
var randomNum = Math.round(Math.random() * 10000);
xhr.open('HEAD', file + "?rand=" + randomNum, true);
xhr.send();
xhr.addEventListener("readystatechange", processRequest, false);
function processRequest(e) {
if (xhr.readyState == 4) {
if (xhr.status >= 200 && xhr.status < 304) {
alert("connection ok");
} else {
alert("connection doesn't exist!");
}
}
}
}
Its not working, showing:
connection doesn't exist!
if I pass "localhost/myApp" Instead of "www.google.com", it works fine, but if I pass my IP instead of "localhost", it's not working that time again.
Upvotes: 2
Views: 1724
Reputation: 15566
You can use a proxy server with CORS enabled if your requirement is simple. You can even have a proxy server of your own setup with a similar service. If you are just checking uptime of a single server, then it is better to enable CORS in your server for this service.
function doesConnectionExist(url) {
var xhr = new XMLHttpRequest();
var file = "http://cors-anywhere.herokuapp.com/" + url;
var randomNum = Math.round(Math.random() * 10000);
xhr.open('HEAD', file + "?rand=" + randomNum, true);
xhr.send();
xhr.addEventListener("readystatechange", processRequest, false);
function processRequest(e) {
if (xhr.readyState == 4) {
console.log(url, xhr.status);
if (xhr.status >= 200 && xhr.status < 304) {
console.log("connection ok");
} else {
console.log("connection doesn't exist!");
}
}
}
}
doesConnectionExist("http://www.marotikkaya.in");
doesConnectionExist("http://www.google.com");
Upvotes: 1