The other day I was developing small client-server application where I needed to check using Javascript on the client’s side whether active Internet connection exists, before submitting request to the server.
Javascript does not allow you to do ping, and even so many websites protect against ping requests (ICMP echo), so I had to come up with some alternatives.
One of the nice solutions that I have found is to create an Image object and to specify as image source, URL to an image located on a remote server. Then to test, if the newly created Image object has height or width greater than zero.
If it is greater, what it means is that there is active Internet connection, since it was possible to create Image object using image or icon located on a remote server.
The downside here is that path to the image or image filename may change in the future on the target remote server, and as a result of that your Javascript function will stop working.
While thinking what image should I link to, I decided to use Google’s favicon. I tend to think that the favicon is not something that is going to change very often. I also considered to use Goggle logo, but favicon is much smaller in size.
(Another thing worth remembering is to allow some time to retrieve the remote image, which is another reason why I went for the favicon).
The solution is:
function testConnection() {
var googleFavIcon = new Image();
googleFavIcon.src =
"http://www.google.com/favicon.ico";
if(googleFavIcon.height>0) {
//do something
}
else {
//warn user
}
}
Just keep in mind, that the remote image is cached once you got it. If you decide to test connection again, you have to make sure that you are not using the cached image, but trying to retrieve it again from the remote server. To prevent caching, you can add some random parameter to the URL:
http://www.google.com/favicon.ico?param=[random-value]
loading...
Related posts:
- How to Prevent iFrame Breakaway
Few days ago I was searching for a solution to the problem I’ve encountered – I needed to prevent a third party page...
