internet的JavaScript检查
我有一个web应用程序,需要在调用下面的功能时检查web浏览器是否连接到internetinternet的JavaScript检查,javascript,Javascript,我有一个web应用程序,需要在调用下面的功能时检查web浏览器是否连接到internet function ping(){ var xhttp = new XMLHttpRequest(); xhttp.onreadystatechange = function() { if (this.readyState == 4 && this.status == 200) { // Typical action to be perf
function ping(){
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
// Typical action to be performed when the document is ready:
console.log("response: " + xhttp.responseText);
}
};
xhttp.open("GET", "http://www.google.com", true);
xhttp.send();
}
下面是google chrome控制台的功能结果。这有点管用
连接到internet时:
未能加载:否
“Access Control Allow Origin”标头出现在请求的服务器上
资源因此,不允许访问源“null”
没有internet连接时:
得到0
所以,如果我能区分这些错误,我的函数会存在,但我也有一种感觉,这是一种完全奇怪的方法
是否有更好/更简单的方法检查internet连接?更新
运行脚本,尝试断开internet连接
window.addEventListener'load',函数{
var status=document.getElementByIdstatus;
var log=document.getElementByIdlog;
函数updateOnlineStatusevent{
var条件=navigator.onLine?在线:离线;
status.className=条件;
status.innerHTML=condition.toUpperCase;
log.insertadjacenthlbeforeend,事件:+Event.type+;状态:+condition;
}
window.addEventListener'online',UpdateOnline状态;
addEventListener'offline',updateOnlineStatus;
};
地位{
位置:固定;
宽度:100%;
字体:粗体1em无衬线;
颜色:FFF;
填充:0.5em;
}
日志{
填充物:2.5em 0.5em 0.5em;
字体:1em无衬线;
}
.在线{
背景:绿色;
}
.离线{
背景:红色;
}
这是一个测试,请尝试断开internet的连接。navigator.onLine解决方案是其中的一部分,但如果计算机连接到本身未连接到internet的wifi路由器,则不会给出正确的结果 我发现CORS是我的方法的问题,多亏了评论中的人,我发现了一种更好的方法,可以使用@Alnitak这样的图像资源。有助于了解如何处理映像加载和错误回调 下面是一些简单的代码来说明我是如何做到的 看到丹尼尔的笔了吗 HTML
可能重复的Javascript可能重复的Javascript有一个api来检测是否存在internet:请求一个图像资源而不是使用AJAX,这样您就不会受到在第一篇引用的文本中产生错误的相同CORS限制。我个人不会使用这个答案,因为文中提到了,如果确实要确定浏览器的联机状态,则应开发其他检查方法。这意味着window.navigator.online不是检查真实internet连接的可靠方法。只需使用返回的原始错误代码即可。这可能更具解释性。感谢您的详细说明,但是您对第一篇提到的文章有何看法?虽然您可以假设浏览器在返回假值时处于脱机状态,但不能假设真值必然意味着浏览器可以访问internet。您可能会得到误报…?但是是的,AJAX可以更可靠,但我们在这里尝试更简单。正确的验证总是首选问题是,如果您断开与internet的连接,但仍保持与LAN的连接,甚至与实际上没有连接的联机适配器的连接,则浏览器会认为您处于联机状态,但仍然无法加载要加载的资源。然而,总比没有好。谢谢你更新答案!
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>InternetConnection</title>
<script src="InternetConnection.js" type="text/javascript"></script>
</head>
<body onload="initialize();">
<h1 id="status"></h1>
</body>
</html>
var internetAccess = true;
// Goes to Google and tries to get an image, changes a flag, then calls to update view
function checkInternet(){
var img = new Image();
img.onload = function(){
internetAccess = true;
updateView();
};
img.onerror = function(){
internetAccess = false;
updateView();
};
// The browser will cache images (and you'll always get a successful 'onload') unless you request a 'dummmy' query ('?dummy=UNIQUE_NUMBERS') so that every image is unique.
img.src = 'https://www.google.com/images/branding/googlelogo/1x/googlelogo_color_272x92dp.png'+"?dummy="+new Date().getTime();
}
function updateView(){
var isOnline = navigator.onLine && internetAccess;
if(isOnline){
console.log("Connected!");
document.body.bgColor = 'darkgreen';
document.getElementById("status").innerHTML = "CONNECTED :)";
// Retest connection to ensure is truly connected... I commented this out since I do not really want to constantly check in my case (I just register a click listener so that I don't have hundreds of requests of small images over an hour if I leave the webpage running).
// checkSpawner();
}else{
console.log("NOT connected");
document.body.bgColor = 'yellow';
document.getElementById("status").innerHTML = "NOT CONNECTED :(";
// Retest connection until it succeeds
checkSpawner();
}
}
// Check internet connection every 5 seconds
function checkSpawner(){
console.log("checking for internet...");
setTimeout(checkInternet, 5000);
}
// Setup listeners for when the connection is disrupted
function initialize(){
window.addEventListener("online", checkInternet);
window.addEventListener("offline", checkInternet);
checkInternet();
}