[Javascript] Detect internet connection

Paul Novitski paul at novitskisoftware.com
Wed Feb 16 12:47:11 CST 2005


At 11:51 PM 2/15/2005, Tim Burgan wrote:
>Is is possible to write a script that can detect if a user is connected to 
>the internet?

Tim,

It would be helpful to know the purpose of your connection check.  Do you 
want to prevent a form submission in the absence of a connection, or...?

I assume you're postulating a script in a page that wants to know whether 
the page it's attached to was called up from cache or downloaded from the 
net, and if it's freshly downloaded whether the connection has subsequently 
dropped.

I would think that the image-downloading technique would give a false 
positive if the browser were retrieving the image from cache on the client, 
so you'd have to have a server-side script that responded to an unique 
transient uri:

         <img id="checkcnx" src="" />
         ...
         var oImg = document.getElementById("checkcnx");
         oImg.src = oDate.getTime() + ".jpg"

The img src is generated on the fly by Javascript and would always be 
different; this would trigger a 404 error (file not found) on the server 
which the server-side script could intercept, parse, and respond to by 
supplying an existing small (1kb).  Because the img src would change each 
time it was called, I think this would get around the image caching problem 
of a fixed uri.

If all you need to do is find out whether the page was called up from 
cache, you could do something like this:  Include two date & time fields on 
the page, one supplied by the server when it downloads it and another 
supplied by JavaScript when the page begins to download or has finished 
downloading.  If the difference between these two times (perhaps adjusting 
for time zone differences between server & client) is more than N seconds, 
the page is probably from cache.

Paul 





More information about the Javascript mailing list