【发布时间】:2014-08-19 23:55:54
【问题描述】:
好的,我收到了这个案子。我在 angular.js 上构建了这个应用程序,并在 node.js 上构建了后端......它无论如何都可以正常工作。
客户端与互联网的连接很糟糕。它时不时地在线和离线。我需要做的是 ping 我的服务器以检查其连接的例程。如果失败,我需要 ping 到其他东西(比如说:google.com),这样我可以检查两件事:
1.- 我的服务器在线(或不在线) 2.- 客户端没有网络连接。
使用此例程 Ping 到服务器可以正常工作:
function hostReachable(host) { // Handle IE and more capable browsers
var xhr = new ( window.ActiveXObject || XMLHttpRequest )( "Microsoft.XMLHTTP" );
var status;
// Open new request as a HEAD to the root hostname with a random param to bust the cache
xhr.open( "GET", "//" + host + "/?rand=" + Math.floor((1 + Math.random()) * 0x10000), false);
// Issue request and handle response
try { xhr.send(); return (xhr.status >= 200 && xhr.status < 300 || xhr.status === 304); }
catch (error) { return false; }
}
}
function check() {
if (!hostReachable(window.location.host)) {
if (!hostReachable('www.google.co.ve')) {
alert('No se pudo establecer conexión con el sistema. Revise su conexion a internet.');
} else {
alert('Existe un problema con el sistema. Por favor contacto a los administradores.');
}
} else {
console.log('Connected...');
}
}
check();
交易是检查 google.com 会出现跨域问题。所以问题很简单。有没有办法像这样检查互联网连接?
【问题讨论】:
-
对最终用户有什么明显的区别吗?您是否希望他们给您发送电子邮件并告诉您您的服务器已离线,以便您重新启动它?
-
navigator.online 超越了您的第一个任务。
-
@dandavis — 根据MDN,navigator.onLine 不是特别可靠,应采用备份方法(例如,根据 OP)。
-
@RobG:非常可靠的是,如果 navigator.online===false,你没有互联网。如果是真的,那么 OP 的第二步应该处理潜在的误报。
-
你可以使用 xhr.onerror() 来避免 try/catchy yuckiness。
标签: javascript angularjs