Check If Internet Connection Exists in JavaScript

I am always taking notes on my phone, and I wanted to sync them to a web service that I created for fun. As part of that, I needed to ensure I had an internet connection before making the web request. I wrote about how I did that in this tutorial.

:megaman:

I don’t know java, so even a simple thing becomes impossible for me, what i would like to do is to use this code on a simple link, if internet exists open the link if not show a message, is there some example of this somewhere, i was not able to find. Second i would like to do the same for Iframes if internet exists show the contents of the iframe, if not show message.

In another post i found this:
You can trigger it on anything you want. It all depends on how frequently you want to check for the connection. I don’t know of any really efficient ways outside of a timer or having code on every button that triggers this check :slight_smile:

i don’t mind having code on every button, but what would the code be?

Update,
I did find a way how to open a link instead of the alert by changing it with this: window.location = ‘https://www.google.com’;
but i still would like to change it in a herf and not in the java code if possible

I read that your code must be on a server to work, well i tried on a server but i always get no internet connection
this is an exact copy of your code:
http://www.8ap.eu/checkintcon/
i need it on a web app, and i get the same, always no connection.
plus google tells me:
Synchronous XMLHttpRequest on the main thread is deprecated because of its detrimental effects to the end user’s experience. For more help, check https://xhr.spec.whatwg.org/.
i don’t know if that is a problem or not?

benedetto - the synchronous issue is something to address, so I’ve updated the code snippet in the tutorial to use true for the last argument:

xhr.open('HEAD', file + "?rand=" + randomNum, true);

Try making that change and seeing if the request works. We can then address your other issue next once we got that part figured out :slight_smile:

I did the change to true, but same result

So sorry! I see what the problem was. Replace the file variable with this:

var file = "https://www.kirupa.com/blank.png";

Because the URL in my example started of with just // instead of https://, the request inherited your site’s http:// instead. That won’t work, for the URL needs to be https :slight_smile:

i see, well i don’t have an https at the moment, i tried putting the check image fine on the same domain, but still the same, but any way so this means it would never work in a webapp, because it wouldn’e be on a server but on a smartphone?

It should work inside a webapp as well. When you mention webapp, are you referring to a Cordova app? Or is it just a browser-based app running on a mobile device? I fiddled with my earlier code, and I had a bug in it. It won’t work when set to run asynchronously, but I’ve updated it to use the onload event.

Below is a small example:

function doesConnectionExist() {
    var xhr = new XMLHttpRequest();
	var file = "https://www.kirupa.com/blank.png";
	var randomNum = Math.round(Math.random() * 10000);
	
	xhr.open('HEAD', file + "?rand=" + randomNum, true);
	
	xhr.onload = function (e) {
		if (xhr.status >= 200 && xhr.status < 304) {
	        alert("yay!");
	    } else {
	        alert("no!!!");
	    }
	};
	xhr.send();
}

If you try this on your server and just call doesConnectionExist, the code should work! At least, I’m fairly confident it will :stuck_out_tongue:

Cheers,
Kirupa

If the above solution doesn’t work, here is (I think) an even better approach:

function doesConnectionExist() {
    var xhr = new XMLHttpRequest();
    var file = "https://www.kirupa.com/blank.png";
    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 exists!");
            } else {
                alert("connection doesn't exist!");
            }
        }
    }
}

This approach is better suited for asynchronous requests by using the readyState property. I don’t know if this will yield you a different response than what you’ve seen earlier, but how are you running your web app? Is it installed (Cordova, Phonegap, Webview, etc.), or are you running it via the browser?

Thanks,
Kirupa

Yes i’m using something like Cordova, i think it’s Phonegap but i’m not sure, because i send it to compile using a web service, but anyway the last example did the trick, the first one i couldn’t get it to work, thanks for the time. I did find out that using your image for the check didn’t work, so i changed it to one on the same server and it worked, now i have a question, instead of the image would it be possible to ping google and if you get the 200 response code ok if not ko, The working example is at: http://www.8ap.eu/checkintcon/

You can try it and find out. The safest bet is to point to a resource on your own server. That way you don’t have to worry about any security settings changing where Google starts blocking requests to their server. Not a problem if you are running on a server and can make an update very quickly to point to another location. More of an issue if you are dealing with deployed apps on a device :slight_smile:

I’m not able to even try to write something like that, but thanks any way for the explanation, i just asked because i did something similar with Mit app inventor ( coding with blocks ) and i used the 200 code from google to check for internet.

P.s. if you have nothing to do, would you have a look at this:


Thanks.