检测互联网连接是否离线?

发布于 2024-07-08 03:29:38 字数 35 浏览 8 评论 0原文

如何在 JavaScript 中检测互联网连接是否离线?

How can I detect if the internet connection is offline in JavaScript?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(24

心的憧憬 2024-07-15 03:29:39

我必须为经常与学校合作的客户制作一个网络应用程序(基于ajax),这些学校的互联网连接通常很差,我使用这个简单的功能来检测是否有连接,效果非常好!

我使用 CodeIgniter 和 Jquery:

function checkOnline() {
    setTimeout("doOnlineCheck()", 20000);
}

function doOnlineCheck() {
    //if the server can be reached it returns 1, other wise it times out
    var submitURL = $("#base_path").val() + "index.php/menu/online";

    $.ajax({
        url : submitURL,
        type : "post",
        dataType : "msg",
        timeout : 5000,
        success : function(msg) {
            if(msg==1) {
                $("#online").addClass("online");
                $("#online").removeClass("offline");
            } else {
                $("#online").addClass("offline");
                $("#online").removeClass("online");
            }
            checkOnline();
        },
        error : function() {
            $("#online").addClass("offline");
            $("#online").removeClass("online");
            checkOnline();
        }
    });
}

I had to make a web app (ajax based) for a customer who works a lot with schools, these schools have often a bad internet connection I use this simple function to detect if there is a connection, works very well!

I use CodeIgniter and Jquery:

function checkOnline() {
    setTimeout("doOnlineCheck()", 20000);
}

function doOnlineCheck() {
    //if the server can be reached it returns 1, other wise it times out
    var submitURL = $("#base_path").val() + "index.php/menu/online";

    $.ajax({
        url : submitURL,
        type : "post",
        dataType : "msg",
        timeout : 5000,
        success : function(msg) {
            if(msg==1) {
                $("#online").addClass("online");
                $("#online").removeClass("offline");
            } else {
                $("#online").addClass("offline");
                $("#online").removeClass("online");
            }
            checkOnline();
        },
        error : function() {
            $("#online").addClass("offline");
            $("#online").removeClass("online");
            checkOnline();
        }
    });
}
橙味迷妹 2024-07-15 03:29:39

我认为这是一个非常简单的方法。

var x = confirm("Are you sure you want to submit?");
if (x) {
  if (navigator.onLine == true) {
    return true;
  }
  alert('Internet connection is lost');
  return false;
}
return false;

I think it is a very simple way.

var x = confirm("Are you sure you want to submit?");
if (x) {
  if (navigator.onLine == true) {
    return true;
  }
  alert('Internet connection is lost');
  return false;
}
return false;
花开半夏魅人心 2024-07-15 03:29:39

navigator.onLine 这样的方法的问题是它们与某些浏览器和移动版本不兼容,对我帮助很大的一个选项是使用经典的 XMLHttpRequest 方法并且还预见到文件存储在缓存中的可能情况,响应 XMLHttpRequest.status 大于 200 且小于 304。

这是我的代码:

 var xhr = new XMLHttpRequest();
 //index.php is in my web
 xhr.open('HEAD', 'index.php', true);
 xhr.send();

 xhr.addEventListener("readystatechange", processRequest, false);

 function processRequest(e) {
     if (xhr.readyState == 4) {
         //If you use a cache storage manager (service worker), it is likely that the
         //index.php file will be available even without internet, so do the following validation
         if (xhr.status >= 200 && xhr.status < 304) {
             console.log('On line!');
         } else {
             console.log('Offline :(');
         }
     }
}

The problem of some methods like navigator.onLine is that they are not compatible with some browsers and mobile versions, an option that helped me a lot was to use the classic XMLHttpRequest method and also foresee the possible case that the file was stored in cache with response XMLHttpRequest.status is greater than 200 and less than 304.

Here is my code:

 var xhr = new XMLHttpRequest();
 //index.php is in my web
 xhr.open('HEAD', 'index.php', true);
 xhr.send();

 xhr.addEventListener("readystatechange", processRequest, false);

 function processRequest(e) {
     if (xhr.readyState == 4) {
         //If you use a cache storage manager (service worker), it is likely that the
         //index.php file will be available even without internet, so do the following validation
         if (xhr.status >= 200 && xhr.status < 304) {
             console.log('On line!');
         } else {
             console.log('Offline :(');
         }
     }
}
眼藏柔 2024-07-15 03:29:39

我正在寻找一种客户端解决方案来检测互联网是否已关闭或我的服务器是否已关闭。 我发现的其他解决方案似乎总是依赖于第三方脚本文件或图像,对我来说,这似乎经不起时间的考验。 外部托管脚本或图像将来可能会发生变化并导致检测代码失败。

我找到了一种通过查找带有 404 代码的 xhrStatus 来检测它的方法。 另外,我使用JSONP来绕过CORS限制。 404 以外的状态代码表明互联网连接无法正常工作。

$.ajax({
    url:      'https://www.bing.com/aJyfYidjSlA' + new Date().getTime() + '.html',
    dataType: 'jsonp',
    timeout:  5000,

    error: function(xhr) {
        if (xhr.status == 404) {
            //internet connection working
        }
        else {
            //internet is down (xhr.status == 0)
        }
    }
});

I was looking for a client-side solution to detect if the internet was down or my server was down. The other solutions I found always seemed to be dependent on a 3rd party script file or image, which to me didn't seem like it would stand the test of time. An external hosted script or image could change in the future and cause the detection code to fail.

I've found a way to detect it by looking for an xhrStatus with a 404 code. In addition, I use JSONP to bypass the CORS restriction. A status code other than 404 shows the internet connection isn't working.

$.ajax({
    url:      'https://www.bing.com/aJyfYidjSlA' + new Date().getTime() + '.html',
    dataType: 'jsonp',
    timeout:  5000,

    error: function(xhr) {
        if (xhr.status == 404) {
            //internet connection working
        }
        else {
            //internet is down (xhr.status == 0)
        }
    }
});
请恋爱 2024-07-15 03:29:39

如何使用 no-cors 向 google.com 发送不透明的 http 请求?

    fetch('https://google.com', {
        method: 'GET', // *GET, POST, PUT, DELETE, etc.
        mode: 'no-cors',
    }).then((result) => {
        console.log(result)
    }).catch(e => {
        console.error(e)
    })

设置 no-cors 的原因是,即使在我的电脑上禁用网络连接,我也会收到 cors 错误。 所以无论有没有互联网连接,我都会被阻止。 添加 no-cors 会使请求变得不透明,这看起来似乎绕过了 cors,并允许我简单地检查是否可以连接到 Google。

仅供参考:我在这里使用 fetch 来发出 http 请求。
https://www.npmjs.com/package/fetch

How about sending an opaque http request to google.com with no-cors?

    fetch('https://google.com', {
        method: 'GET', // *GET, POST, PUT, DELETE, etc.
        mode: 'no-cors',
    }).then((result) => {
        console.log(result)
    }).catch(e => {
        console.error(e)
    })

The reason for setting no-cors is that I was receiving cors errors even when disbaling the network connection on my pc. So I was getting cors blocked with or without an internet connection. Adding the no-cors makes the request opaque which apperantly seems to bypass cors and allows me to just simply check if I can connect to Google.

FYI: Im using fetch here for making the http request.
https://www.npmjs.com/package/fetch

口干舌燥 2024-07-15 03:29:39

我的方式。

<!-- the file named "tt.jpg" should exist in the same directory -->

<script>
function testConnection(callBack)
{
    document.getElementsByTagName('body')[0].innerHTML +=
        '<img id="testImage" style="display: none;" ' +
        'src="tt.jpg?' + Math.random() + '" ' +
        'onerror="testConnectionCallback(false);" ' +
        'onload="testConnectionCallback(true);">';

    testConnectionCallback = function(result){
        callBack(result);

        var element = document.getElementById('testImage');
        element.parentNode.removeChild(element);
    }    
}
</script>

<!-- usage example -->

<script>
function myCallBack(result)
{
    alert(result);
}
</script>

<a href=# onclick=testConnection(myCallBack);>Am I online?</a>

My way.

<!-- the file named "tt.jpg" should exist in the same directory -->

<script>
function testConnection(callBack)
{
    document.getElementsByTagName('body')[0].innerHTML +=
        '<img id="testImage" style="display: none;" ' +
        'src="tt.jpg?' + Math.random() + '" ' +
        'onerror="testConnectionCallback(false);" ' +
        'onload="testConnectionCallback(true);">';

    testConnectionCallback = function(result){
        callBack(result);

        var element = document.getElementById('testImage');
        element.parentNode.removeChild(element);
    }    
}
</script>

<!-- usage example -->

<script>
function myCallBack(result)
{
    alert(result);
}
</script>

<a href=# onclick=testConnection(myCallBack);>Am I online?</a>
尐偏执 2024-07-15 03:29:39

现代打字稿方法:

/**
 * @example
 * const isOnline = await isGoogleOnline();
 */
async function isGoogleOnline(): Promise<boolean> {
    return new Promise((resolve, reject) => {
        // approach taken from https://github.com/HubSpot/offline/blob/master/js/offline.js#L223
        const img = document.createElement('img');
        img.onerror = () => {
            // calling `reject` basically means `throw` if using `await`.
            // Instead, we'll just resovle with `false`. (https://www.swyx.io/errors-not-exceptions)
            resolve(false);
        };
        img.onload = () => {
            resolve(true);
        };
        img.src = 'https://www.google.com/favicon.ico?_=' + ((new Date()).getTime());
    });
}

如果您的请求失败,并且 navigator.onLine 为 FALSE,您可以放心,您实际上处于离线状态。

如果请求成功,请放心,您实际上已在线。

根据您想要的用户体验,您可能根本不需要太多。

modern typescript approach:

/**
 * @example
 * const isOnline = await isGoogleOnline();
 */
async function isGoogleOnline(): Promise<boolean> {
    return new Promise((resolve, reject) => {
        // approach taken from https://github.com/HubSpot/offline/blob/master/js/offline.js#L223
        const img = document.createElement('img');
        img.onerror = () => {
            // calling `reject` basically means `throw` if using `await`.
            // Instead, we'll just resovle with `false`. (https://www.swyx.io/errors-not-exceptions)
            resolve(false);
        };
        img.onload = () => {
            resolve(true);
        };
        img.src = 'https://www.google.com/favicon.ico?_=' + ((new Date()).getTime());
    });
}

If you have a request fail, and navigator.onLine is FALSE, you can rest assured, you are actually offline.

If a request succeeds, rest assured, you are effectively online.

Depending on your desired user experience, you may not need much here at all.

把人绕傻吧 2024-07-15 03:29:39

只需使用 navigator.onLine 如果这是 true 那么你就在线,否则离线

Just use navigator.onLine if this is true then you're online else offline

还在原地等你 2024-07-15 03:29:39

请求错误中的请求头

$.ajax({
    url: /your_url,
    type: "POST or GET",
    data: your_data,
    success: function(result){
      //do stuff
    },
    error: function(xhr, status, error) {

      //detect if user is online and avoid the use of async
        $.ajax({
            type: "HEAD",
            url: document.location.pathname,
            error: function() { 
              //user is offline, do stuff
              console.log("you are offline"); 
              }
         });
    }   
});

request head in request error

$.ajax({
    url: /your_url,
    type: "POST or GET",
    data: your_data,
    success: function(result){
      //do stuff
    },
    error: function(xhr, status, error) {

      //detect if user is online and avoid the use of async
        $.ajax({
            type: "HEAD",
            url: document.location.pathname,
            error: function() { 
              //user is offline, do stuff
              console.log("you are offline"); 
              }
         });
    }   
});
慵挽 2024-07-15 03:29:39

您可以尝试如果网络连接,这将返回 true

function isInternetConnected(){return navigator.onLine;}

You can try this will return true if network connected

function isInternetConnected(){return navigator.onLine;}
浪推晚风 2024-07-15 03:29:39

是的,您可以使用浏览器导航器 API 检查网络可用性。

const isNetwork = navigator.onLine; 
//  navigator.onLine will return true/false based on your network condition

console.log(isNetwork)

Yes you can check network avilability, by using the browser navigator api.

const isNetwork = navigator.onLine; 
//  navigator.onLine will return true/false based on your network condition

console.log(isNetwork)
如歌彻婉言 2024-07-15 03:29:39

这是我拥有的辅助实用程序的片段。 这是命名空间的 javascript:

network: function() {
    var state = navigator.onLine ? "online" : "offline";
    return state;
}

您应该将其与方法检测一起使用,否则会触发“替代”方法来执行此操作。 时间很快就到了,这就是所需要的一切。 其他方法都是 hack。

Here is a snippet of a helper utility I have. This is namespaced javascript:

network: function() {
    var state = navigator.onLine ? "online" : "offline";
    return state;
}

You should use this with method detection else fire off an 'alternative' way of doing this. The time is fast approaching when this will be all that is needed. The other methods are hacks.

初吻给了烟 2024-07-15 03:29:39

对于两种不同的情况,有 2 个答案:-

  1. 如果您在网站上使用 JavaScript(即;或任何前端部分)
    最简单的方法是:

    导航器对象

    如果浏览器在线,onLine 属性返回 true:

    <脚本> document.getElementById("demo").innerHTML = "navigator.onLine 是 " + navigator.onLine;

  2. 但是如果你在服务器端使用js(即节点等),你可以通过发出失败的XHR请求来确定连接丢失。

    标准方法是重试请求几次。 如果没有通过,则提醒用户检查连接,然后优雅地失败。

There are 2 answers forthis for two different senarios:-

  1. If you are using JavaScript on a website(i.e; or any front-end part)
    The simplest way to do it is:

    <h2>The Navigator Object</h2>
    
    <p>The onLine property returns true if the browser is online:</p>
    
    <p id="demo"></p>
    
    <script>
      document.getElementById("demo").innerHTML = "navigator.onLine is " + navigator.onLine;
    </script>
    

  2. But if you're using js on server side(i.e; node etc.), You can determine that the connection is lost by making failed XHR requests.

    The standard approach is to retry the request a few times. If it doesn't go through, alert the user to check the connection, and fail gracefully.

巴黎盛开的樱花 2024-07-15 03:29:38

几乎所有主流浏览器现在都支持window.navigator.onLine 属性,以及相应的 onlineoffline 窗口事件。 运行以下代码片段进行测试:

console.log('Initially ' + (window.navigator.onLine ? 'on' : 'off') + 'line');

window.addEventListener('online', () => console.log('Became online'));
window.addEventListener('offline', () => console.log('Became offline'));

document.getElementById('statusCheck').addEventListener('click', () => console.log('window.navigator.onLine is ' + window.navigator.onLine));
<button id="statusCheck">Click to check the <tt>window.navigator.onLine</tt> property</button><br /><br />
Check the console below for results:

尝试将系统或浏览器设置为离线/在线模式,并检查日志或 window.navigator.onLine 属性以了解值更改。

但请注意 Mozilla 文档 中的引用:

在 Chrome 和 Safari 中,如果浏览器无法连接到局域网 (LAN) 或路由器,则表示浏览器处于离线状态; 所有其他条件返回true。 因此,虽然您可以假设浏览器在返回 false 值时处于离线状态,但您不能假设 true 值必然意味着浏览器可以访问互联网。 您可能会收到误报,例如计算机运行的虚拟化软件具有始终“连接”的虚拟以太网适配器。 因此,如果你真的想确定浏览器的在线状态,你应该开发额外的手段来检查。

在 Firefox 和 Internet Explorer 中,将浏览器切换到离线模式会发送 false 值。 在 Firefox 41 之前,所有其他条件都返回 true 值; 从 Firefox 41 开始,在 OS X 和 Windows 上,该值将遵循实际的网络连接。

(强调是我自己的)

这意味着如果 window.navigator.onLinefalse (或者您收到 offline 事件),则保证您没有互联网连接。

但是,如果它是 true(或者您收到 online 事件),则最多仅意味着系统已连接到某个网络。 例如,这并不意味着您可以访问互联网。 要检查这一点,您仍然需要使用其他答案中描述的解决方案之一。

我最初打算将其作为格兰特瓦格纳的答案的更新发布,但它似乎编辑太多了,特别是考虑到 2014 年的更新已经不是来自他

Almost all major browsers now support the window.navigator.onLine property, and the corresponding online and offline window events. Run the following code snippet to test it:

console.log('Initially ' + (window.navigator.onLine ? 'on' : 'off') + 'line');

window.addEventListener('online', () => console.log('Became online'));
window.addEventListener('offline', () => console.log('Became offline'));

document.getElementById('statusCheck').addEventListener('click', () => console.log('window.navigator.onLine is ' + window.navigator.onLine));
<button id="statusCheck">Click to check the <tt>window.navigator.onLine</tt> property</button><br /><br />
Check the console below for results:

Try setting your system or browser in offline/online mode and check the log or the window.navigator.onLine property for the value changes.

Note however this quote from Mozilla Documentation:

In Chrome and Safari, if the browser is not able to connect to a local area network (LAN) or a router, it is offline; all other conditions return true. So while you can assume that the browser is offline when it returns a false value, you cannot assume that a true value necessarily means that the browser can access the internet. You could be getting false positives, such as in cases where the computer is running a virtualization software that has virtual ethernet adapters that are always "connected." Therefore, if you really want to determine the online status of the browser, you should develop additional means for checking.

In Firefox and Internet Explorer, switching the browser to offline mode sends a false value. Until Firefox 41, all other conditions return a true value; since Firefox 41, on OS X and Windows, the value will follow the actual network connectivity.

(emphasis is my own)

This means that if window.navigator.onLine is false (or you get an offline event), you are guaranteed to have no Internet connection.

If it is true however (or you get an online event), it only means the system is connected to some network, at best. It does not mean that you have Internet access for example. To check that, you will still need to use one of the solutions described in the other answers.

I initially intended to post this as an update to Grant Wagner's answer, but it seemed too much of an edit, especially considering that the 2014 update was already not from him.

寄人书 2024-07-15 03:29:38

您可以通过发出失败的 XHR 请求来确定连接是否丢失。

标准方法是重试请求几次。 如果未通过,提醒用户检查连接,然后优雅地失败

旁注:将整个应用程序置于“离线”状态可能会导致处理状态的大量容易出错的工作。无线连接可能会来来去去等。所以你最好的选择可能是优雅地失败,保留数据,并提醒用户......允许他们最终解决连接问题(如果有),并在相当宽恕的情况下继续使用您的应用程序。

旁注:您可以检查像谷歌这样的可靠网站的连接性,但这可能并不完全有用,因为只是尝试提出您自己的请求,因为虽然谷歌可能可用,但您自己的应用程序可能不可用,而且您仍然需要处理自己的连接问题。 尝试向 google 发送 ping 是确认互联网连接本身已关闭的好方法,因此如果该信息对您有用,那么可能值得麻烦。

旁注发送 Ping 可以通过与发出任何类型的双向 ajax 请求相同的方式来实现,但发送 ping 到 google,在本例中,会带来一些挑战。 首先,我们会遇到 Ajax 通信中通常遇到的相同跨域问题。 一种选择是设置服务器端代理,其中我们实际上 ping google(或任何网站),并将 ping 结果返回到应用程序。 这是一个第 22 条规则,因为如果互联网连接确实是问题所在,我们将无法访问服务器,而如果连接问题仅出现在我们自己的域上,我们将无法访问服务器无法区分。 可以尝试其他跨域技术,例如,在页面中嵌入一个指向 google.com 的 iframe,然后轮询 iframe 是否成功/失败(检查内容等)。 嵌入图像可能并不能真正告诉我们任何信息,因为我们需要通信机制的有用响应才能对正在发生的事情得出一个好的结论。 再说一次,确定整个互联网连接的状态可能比其价值更麻烦。 您必须针对您的特定应用程序权衡这些选项。

You can determine that the connection is lost by making failed XHR requests.

The standard approach is to retry the request a few times. If it doesn't go through, alert the user to check the connection, and fail gracefully.

Sidenote: To put the entire application in an "offline" state may lead to a lot of error-prone work of handling state.. wireless connections may come and go, etc. So your best bet may be to just fail gracefully, preserve the data, and alert the user.. allowing them to eventually fix the connection problem if there is one, and to continue using your app with a fair amount of forgiveness.

Sidenote: You could check a reliable site like google for connectivity, but this may not be entirely useful as just trying to make your own request, because while Google may be available, your own application may not be, and you're still going to have to handle your own connection problem. Trying to send a ping to google would be a good way to confirm that the internet connection itself is down, so if that information is useful to you, then it might be worth the trouble.

Sidenote: Sending a Ping could be achieved in the same way that you would make any kind of two-way ajax request, but sending a ping to google, in this case, would pose some challenges. First, we'd have the same cross-domain issues that are typically encountered in making Ajax communications. One option is to set up a server-side proxy, wherein we actually ping google (or whatever site), and return the results of the ping to the app. This is a catch-22 because if the internet connection is actually the problem, we won't be able to get to the server, and if the connection problem is only on our own domain, we won't be able to tell the difference. Other cross-domain techniques could be tried, for example, embedding an iframe in your page which points to google.com, and then polling the iframe for success/failure (examine the contents, etc). Embedding an image may not really tell us anything, because we need a useful response from the communication mechanism in order to draw a good conclusion about what's going on. So again, determining the state of the internet connection as a whole may be more trouble than it's worth. You'll have to weight these options out for your specific app.

那片花海 2024-07-15 03:29:38

IE 8 将支持 window.navigator。 onLine 属性。

但当然这对其他浏览器或操作系统没有帮助。 鉴于了解 Ajax 应用程序中在线/离线状态的重要性,我预测其他浏览器供应商也将决定提供该属性。

在此之前,XHR 或 Image() 请求都可以提供接近您想要的功能的内容。

更新 (2014/11/16)

主要浏览器现在支持此属性,但您的结果会有所不同。

引自 Mozilla 文档

在 Chrome 和 Safari 中,如果浏览器无法连接到局域网 (LAN) 或路由器,则表示浏览器处于离线状态; 所有其他条件返回true。 因此,虽然您可以假设浏览器在返回 false 值时处于离线状态,但您不能假设 true 值必然意味着浏览器可以访问互联网。 您可能会收到误报,例如计算机运行的虚拟化软件具有始终“连接”的虚拟以太网适配器。 因此,如果你真的想确定浏览器的在线状态,你应该开发额外的手段来检查。

在 Firefox 和 Internet Explorer 中,将浏览器切换到离线模式会发送 false 值。 所有其他条件都会返回 true 值。

IE 8 will support the window.navigator.onLine property.

But of course that doesn't help with other browsers or operating systems. I predict other browser vendors will decide to provide that property as well given the importance of knowing online/offline status in Ajax applications.

Until that happens, either XHR or an Image() or <img> request can provide something close to the functionality you want.

Update (2014/11/16)

Major browsers now support this property, but your results will vary.

Quote from Mozilla Documentation:

In Chrome and Safari, if the browser is not able to connect to a local area network (LAN) or a router, it is offline; all other conditions return true. So while you can assume that the browser is offline when it returns a false value, you cannot assume that a true value necessarily means that the browser can access the internet. You could be getting false positives, such as in cases where the computer is running a virtualization software that has virtual ethernet adapters that are always "connected." Therefore, if you really want to determine the online status of the browser, you should develop additional means for checking.

In Firefox and Internet Explorer, switching the browser to offline mode sends a false value. All other conditions return a true value.

把时间冻结 2024-07-15 03:29:38
if (navigator.onLine) {
  alert('online');
} else {
  alert('offline');
}

请参阅 onLine 基本用法

if (navigator.onLine) {
  alert('online');
} else {
  alert('offline');
}

See onLine Basic usage

淡淡の花香 2024-07-15 03:29:38

有多种方法可以做到这一点:

  • AJAX 请求到您自己的网站。 如果该请求失败,则很有可能是连接出现问题。 JQuery 文档中有一个关于 处理失败的 AJAX 请求。 执行此操作时请注意同源政策,这可能会阻止您访问域外的网站。
  • 您可以将 onerror 放入 img 中,例如 >

如果源图像被移动/重命名,此方法也可能会失败,并且通常是不如 ajax 选项的选择。

因此,有几种不同的方法来尝试检测这一点,虽然没有完美的方法,但在缺乏跳出浏览器沙箱并直接访问用户网络连接状态的能力的情况下,它们似乎是最好的选择。

There are a number of ways to do this:

  • AJAX request to your own website. If that request fails, there's a good chance it's the connection at fault. The JQuery documentation has a section on handling failed AJAX requests. Beware of the Same Origin Policy when doing this, which may stop you from accessing sites outside your domain.
  • You could put an onerror in an img, like <img src="http://www.example.com/singlepixel.gif" onerror="alert('Connection dead');" />.

This method could also fail if the source image is moved / renamed, and would generally be an inferior choice to the ajax option.

So there are several different ways to try and detect this, none perfect, but in the absence of the ability to jump out of the browser sandbox and access the user's net connection status directly, they seem to be the best options.

失去的东西太少 2024-07-15 03:29:38

正如 olliej 所说,使用 navigator.onLine 浏览器属性比发送网络请求更好,因此 developer.mozilla.org/En/Online_and_offline_events,甚至老版本的Firefox和IE也支持。

最近,WHATWG 指定添加 onlineoffline 事件,以防您需要对 navigator.onLine 更改做出反应。

另请注意 Daniel Silveira 发布的链接,该链接指出依赖这些信号/属性与服务器同步并不总是一个好主意。

As olliej said, using the navigator.onLine browser property is preferable than sending network requests and, accordingly with developer.mozilla.org/En/Online_and_offline_events, it is even supported by old versions of Firefox and IE.

Recently, the WHATWG has specified the addition of the online and offline events, in case you need to react on navigator.onLine changes.

Please also pay attention to the link posted by Daniel Silveira which points out that relying on those signal/property for syncing with the server is not always a good idea.

◇流星雨 2024-07-15 03:29:38
window.navigator.onLine

是您要寻找的内容,但这里需要添加一些内容,首先,如果您想要继续检查应用程序上的某些内容(例如查看用户是否突然离线,这在大多数情况下是正确的,那么您还需要侦听更改),为此,您向窗口添加事件侦听器以检测任何更改,为了检查用户是否离线,您可以执行以下操作:

window.addEventListener("offline", 
  ()=> console.log("No Internet")
);

并检查是否在线:

window.addEventListener("online", 
  ()=> console.log("Connected Internet")
);
window.navigator.onLine

is what you looking for, but few things here to add, first, if it's something on your app which you want to keep checking (like to see if the user suddenly go offline, which correct in this case most of the time, then you need to listen to change also), for that you add event listener to window to detect any change, for checking if the user goes offline, you can do:

window.addEventListener("offline", 
  ()=> console.log("No Internet")
);

and for checking if online:

window.addEventListener("online", 
  ()=> console.log("Connected Internet")
);
迷途知返 2024-07-15 03:29:38

您可以使用 $.ajax()error 回调,如果请求失败则触发。 如果 textStatus 等于字符串“timeout”,则可能意味着连接已损坏:

function (XMLHttpRequest, textStatus, errorThrown) {
  // typically only one of textStatus or errorThrown 
  // will have info
  this; // the options for this ajax request
}

来自 文档

错误:请求时调用的函数
失败。 该函数传递了三个
参数: XMLHttpRequest 对象,
描述错误类型的字符串
发生的情况和可选的
异常对象(如果发生)。
第二个的可能值
参数(除了空)是“超时”,
“错误”、“未修改”和
“解析器错误”。 这是一个 Ajax 事件

,例如:

 $.ajax({
   type: "GET",
   url: "keepalive.php",
   success: function(msg){
     alert("Connection active!")
   },
   error: function(XMLHttpRequest, textStatus, errorThrown) {
       if(textStatus == 'timeout') {
           alert('Connection seems dead!');
       }
   }
 });

You can use $.ajax()'s error callback, which fires if the request fails. If textStatus equals the string "timeout" it probably means connection is broken:

function (XMLHttpRequest, textStatus, errorThrown) {
  // typically only one of textStatus or errorThrown 
  // will have info
  this; // the options for this ajax request
}

From the doc:

Error: A function to be called if the request
fails. The function is passed three
arguments: The XMLHttpRequest object,
a string describing the type of error
that occurred and an optional
exception object, if one occurred.
Possible values for the second
argument (besides null) are "timeout",
"error", "notmodified" and
"parsererror". This is an Ajax Event

So for example:

 $.ajax({
   type: "GET",
   url: "keepalive.php",
   success: function(msg){
     alert("Connection active!")
   },
   error: function(XMLHttpRequest, textStatus, errorThrown) {
       if(textStatus == 'timeout') {
           alert('Connection seems dead!');
       }
   }
 });
小红帽 2024-07-15 03:29:38

HTML5 应用程序缓存 API 指定 navigator.onLine,目前可在 IE8 beta、WebKit(例如 Safari)nightlies 中使用,并且已在 Firefox 3 中受支持

The HTML5 Application Cache API specifies navigator.onLine, which is currently available in the IE8 betas, WebKit (eg. Safari) nightlies, and is already supported in Firefox 3

厌味 2024-07-15 03:29:38

我知道这个问题已经得到解答,但我想加 10 美分来解释什么是更好的,什么是不好的。

Window.navigator.onLine

我注意到一些答案谈到了这个选项,但他们从未提到任何有关警告的内容。

此选项涉及使用“window.navigator.onLine”这是大多数现代浏览器上可用的浏览器导航器界面下的一个属性。 它实际上不是检查互联网可用性的可行选项,因为首先它以浏览器为中心,其次大多数浏览器以不同的方式实现此属性

在 Firefox 中: 该属性返回一个布尔值,true 表示在线,false 表示离线,但这里需要注意的是
仅当用户点击链接或脚本请求远程页面时,该值才会更新。”因此,如果用户离线并且
您从 js 函数或脚本查询该属性,该属性将
始终返回 true,直到用户点击链接。

在 Chrome 和 Safari 中:如果浏览器无法连接到局域网 (LAN) 或路由器,则表示它处于离线状态; 所有其他
条件返回真。 因此,虽然您可以假设浏览器是
当它返回 false 值时离线,您不能假设 true
值必然意味着浏览器可以访问互联网。 你
可能会出现误报,例如计算机
正在运行具有虚拟以太网的虚拟化软件
始终处于“连接”状态的适配器。

上面的陈述只是想让你知道单靠浏览器是无法判断的。 所以基本上这个选项是不可靠的。

向自己的服务器资源发送请求

This involves making HTTP request to your own server resource and if reachable assume internet availability else the user is offline. There are some few caveats to this option.

  1. 没有服务器可用性是 100% 可靠的,因此,如果由于某种原因无法访问您的服务器,则会错误地认为用户在连接到互联网时处于离线状态。
  2. 对同一资源的多个请求可能会返回缓存的响应,从而使 http 响应结果不可靠。

如果您同意您的服务器始终在线,那么您可以选择此选项。

以下是获取自己资源的简单代码片段:

// This fetches your website's favicon, so replace path with favicon url
// Notice the appended date param which helps prevent browser caching.
fetch('/favicon.ico?d='+Date.now())
  .then(response => {
    if (!response.ok)
      throw new Error('Network response was not ok');

   // At this point we can safely assume the user has connection to the internet
        console.log("Internet connection available"); 
  })
  .catch(error => {
  // The resource could not be reached
        console.log("No Internet connection", error);
  });

向第三方服务器资源发送请求

We all know CORS is a thing.

此选项涉及向外部服务器资源发出 HTTP 请求,如果可以访问,则假设互联网可用,否则用户处于离线状态。 对此的主要警告是跨源资源共享,它是一种限制。 大多数信誉良好的网站都会阻止 CORS 请求,但对于某些网站,您可以随心所欲。

下面是一个获取外部资源的简单片段,与上面相同,但具有外部资源 url:

// Firstly you trigger a resource available from a reputable site
// For demo purpose you can use the favicon from MSN website
// Also notice the appended date param which helps skip browser caching.
fetch('https://static-global-s-msn-com.akamaized.net/hp-neu/sc/2b/a5ea21.ico?d='+Date.now())
  .then(response => {
  // Check if the response is successful
    if (!response.ok)
      throw new Error('Network response was not ok');

// At this point we can safely say the user has connection to the internet
        console.log("Internet available"); 
  })
  .catch(error => {
  // The resource could not be reached
        console.log("No Internet connection", error);
  });

因此,最后对于我的个人项目,我选择了第二个选项,其中涉及请求自己的服务器资源,因为基本上有很多因素可以判断是否存在“互联网”用户设备上的“连接”,不仅仅是来自您的网站容器,也不仅仅是来自有限的浏览器 API。

请记住,您的用户也可能处于某些网站或资源被阻止、禁止和无法访问的环境中,这反过来会影响连接检查的逻辑。 最好的选择是:

  • 尝试访问您自己的服务器上的资源,因为这是您的用户环境(通常我使用网站的图标,因为响应非常轻并且不经常更新)。
  • 如果没有与资源的连接,当您需要通知用户时,只需说“连接错误”或“连接丢失”,而不是假定广泛的“无互联网连接”,这取决于许多因素。

I know this question has already been answered but i will like to add my 10 cents explaining what's better and what's not.

Window.navigator.onLine

I noticed some answers spoke about this option but they never mentioned anything concerning the caveat.

This option involves the use of "window.navigator.onLine" which is a property under Browser Navigator Interface available on most modern browsers. It is really not a viable option for checking internet availability because firstly it is browser centric and secondly most browsers implement this property differently.

In Firefox: The property returns a boolean value, with true meaning online and false meaning offline but the caveat here is that
"the value is only updated when the user follows links or when a script requests a remote page." Hence if the user goes offline and
you query the property from a js function or script, the property will
always return true until the user follows a link.

In Chrome and Safari: If the browser is not able to connect to a local area network (LAN) or a router, it is offline; all other
conditions return true. So while you can assume that the browser is
offline when it returns a false value, you cannot assume that a true
value necessarily means that the browser can access the internet. You
could be getting false positives, such as in cases where the computer
is running a virtualization software that has virtual ethernet
adapters that are always "connected".

The statements above is simply trying to let you know that browsers alone cannot tell. So basically this option is unreliable.

Sending Request to Own Server Resource

This involves making HTTP request to your own server resource and if reachable assume internet availability else the user is offline. There are some few caveats to this option.

  1. No server availability is 100% reliant, hence if for some reason your server is not reachable it would be falsely assumed that the user is offline whereas they're connected to the internet.
  2. Multiple request to same resource can return cached response making the http response result unreliable.

If you agree your server is always online then you can go with this option.

Here is a simple snippet to fetch own resource:

// This fetches your website's favicon, so replace path with favicon url
// Notice the appended date param which helps prevent browser caching.
fetch('/favicon.ico?d='+Date.now())
  .then(response => {
    if (!response.ok)
      throw new Error('Network response was not ok');

   // At this point we can safely assume the user has connection to the internet
        console.log("Internet connection available"); 
  })
  .catch(error => {
  // The resource could not be reached
        console.log("No Internet connection", error);
  });

Sending Request to Third-Party Server Resource

We all know CORS is a thing.

This option involves making HTTP request to an external server resource and if reachable assume internet availability else the user is offline. The major caveat to this is the Cross-origin resource sharing which act as a limitation. Most reputable websites blocks CORS requests but for some you can have your way.

Below a simple snippet to fetch external resource, same as above but with external resource url:

// Firstly you trigger a resource available from a reputable site
// For demo purpose you can use the favicon from MSN website
// Also notice the appended date param which helps skip browser caching.
fetch('https://static-global-s-msn-com.akamaized.net/hp-neu/sc/2b/a5ea21.ico?d='+Date.now())
  .then(response => {
  // Check if the response is successful
    if (!response.ok)
      throw new Error('Network response was not ok');

// At this point we can safely say the user has connection to the internet
        console.log("Internet available"); 
  })
  .catch(error => {
  // The resource could not be reached
        console.log("No Internet connection", error);
  });

So, Finally for my personal project i went with the 2nd option which involves requesting own server resource because basically there are many factors to tell if there is "Internet Connection" on a user's device, not just from your website container alone nor from a limited browser api.

Remember your users can also be in an environment where some websites or resources are blocked, prohibited and not accessible which in turn affects the logic of connectivity check. The best bet will be:

  • Try to access a resource on your own server because this is your users environment (Typically i use website's favicon because the response is very light and it is not frequently updated).
  • If there is no connection to the resource, simply say "Error in connection" or "Connection lost" when you need to notify the user rather than assume a broad "No internet connection" which depends on many factors.
折戟 2024-07-15 03:29:38

对您的域进行 ajax 调用是检测您是否离线的最简单方法,

$.ajax({
      type: "HEAD",
      url: document.location.pathname + "?param=" + new Date(),
      error: function() { return false; },
      success: function() { return true; }
   });

这只是为了给您提供概念,它应该得到改进。

例如 error=404 应该仍然意味着你在线

an ajax call to your domain is the easiest way to detect if you are offline

$.ajax({
      type: "HEAD",
      url: document.location.pathname + "?param=" + new Date(),
      error: function() { return false; },
      success: function() { return true; }
   });

this is just to give you the concept, it should be improved.

E.g. error=404 should still mean that you online

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文