views:

61

answers:

2

Hi everyone,

I'm trying to accurately detect when the browser goes offline, using the HTML5 online and offline events.

Here's my code:

<script>
    // FIREFOX
    $(window).bind("online", applicationBackOnline); 
    $(window).bind("offline", applicationOffline);

    //IE
    window.onload = function() {
        document.body.ononline = IeConnectionEvent;
        document.body.onoffline = IeConnectionEvent;
    } 
</script>

It works fine when I just hit "Work offline" on either Firefox or IE, but it's kind of randomly working when I actually unplug the wire.

What's the best way to detect this change? I'd like to avoid repeating ajax calls with timeouts.

Thank you!

+2  A: 

Hey,

In HTML5 you can use the navigator.onLine property. Look here:

http://www.w3.org/TR/offline-webapps/#related

Probably your current behavior is random as the javascript only ready the "browser" variable and then knows if you're offline and online, but it doesn't actually check the Network Connection.

Let us know if this is what you're looking for.

Kind Regards,

Trefex
Thanks for your help Trefex. I changed my code, and now only check the navigator.onLine property, however I get the same behavior as before. Please have a look at mattbasta's comment.
Pedro
Hi Pedro, I agree with mattbasta but I hoped it would work for you :) I would definitely use the Ajax method to query some URL that you know is always up and then you'd know if a connection is lost or not.On another note, why do you require the accurate detection of the online / offline status ? Maybe if we'd know more, there would be another solution for your issue.Let us know,
Trefex
Ok, thanks :) I just thought it'd be better for the user if the application was able to auto-detect a change in connectivity (no need to manually enable the offline mode in FF or IE). This way, when the application goes offline, it will use its local cache instead of querying the server. I found this post from John Resig, which pretty much explains why this doesn't work: http://ejohn.org/blog/offline-events/
Pedro
Thank you for that blog post. Relly in depth analysis and right to the point. I think what you want to achieve it's best if you query some server (maybe your own) and then switch to local cache when there is x number of timeouts. What do you think ?
Trefex
Yeah I guess that is the best option - given the current state of the art. I hope that all browser will eventually be able to detect the actual loss of connection by themselves: using navigator.onLine is pretty simple and this shouldn't be more complex. Don't you think?
Pedro
Yes totally... :)
Trefex
+1  A: 
if(!(navigator.onLine))
alert("U'r Browser seems to be Offline! \n Please,Disable Work Offline and Reload page");
Bhanu