开发者

Detect Internet Connection as in Gmail Javascript

开发者 https://www.devze.com 2023-01-21 09:31 出处:网络
I\'m creating an HTML autorun. There is no restriction in using javascript as it will be run from XULRunner. I want a way to detect if internet connection exist or not. This doesn\'t work for me

I'm creating an HTML autorun. There is no restriction in using javascript as it will be run from XULRunner. I want a way to detect if internet connection exist or not. This doesn't work for me

$(document).ready(function() {
    var online = navigator.onLine;

// a workaround for a flaw in the demo system (http://dev.jqueryui.com/ticket/4375), ignore!
function doit() {
开发者_如何学运维if (navigator.onLine(connected)){     
alert("YES!");
} else {    
 alert("NO!"); 
}  
} 

Is there a better way?

Update: Came to know that the code above only detects the browser state and not if internet is available. For me the contact form in the autorun has to check if internet is connected and alert the user.


Use an XMLHttpRequest in javascript to request a small file from your server. If the request returns an error or times out, then the site is probably unreachable. If you don't have a particular webserver to test on, you could use something with a high degree of reliability, like the Google server.

Though, if you do use the Google server that wouldn't necessarily correspond to your own site being reachable, it would just mean that you are able to connect to the internet. Your own site may down\otherwise unavailable.

0

精彩评论

暂无评论...
验证码 换一张
取 消