检查 Internet 连接是否存在 Javascript?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2384167/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 00:02:25  来源:igfitidea点击:

Check if Internet Connection Exists with Javascript?

javascriptjquerybrowserofflineinternet-connection

提问by Lance Pollard

How do you check if there is an internet connection using Javascript? That way I could have some conditionals saying "use the google cached version of JQuery during production, use either that or a local version during development, depending on the internet connection".

你如何使用Javascript检查是否有互联网连接?这样我可以有一些条件说“在生产过程中使用谷歌缓存的 JQuery 版本,在开发过程中使用该版本或本地版本,具体取决于互联网连接”。

回答by JP Silvashy

The best option for your specific case might be:

您的特定情况的最佳选择可能是:

Right before your close </body>tag:

就在您的关闭</body>标签之前:

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script>window.jQuery || document.write('<script src="js/vendor/jquery-1.10.2.min.js"><\/script>')</script>

This is probably the easiest way given that your issue is centered around jQuery.

鉴于您的问题以 jQuery 为中心,这可能是最简单的方法。

If you wanted a more robust solution you could try:

如果您想要一个更强大的解决方案,您可以尝试:

var online = navigator.onLine;

Read more about the W3C's spec on offline web apps, however be aware that this will work best in modern web browsers, doing so with older web browsers may not work as expected, or at all.

阅读有关W3C 关于离线 Web 应用程序的规范的更多信息,但请注意,这在现代 Web 浏览器中效果最佳,在较旧的 Web 浏览器中这样做可能无法按预期工作,或者根本无法正常工作。

Alternatively, an XHR request to your own server isn't that bad of a method for testing your connectivity. Considering one of the other answers state that there are too many points of failure for an XHR, if your XHR is flawed when establishing it's connection then it'll also be flawed during routine use anyhow. If your site is unreachable for any reason, then your other services running on the same servers will likely be unreachable also. That decision is up to you.

或者,向您自己的服务器发送 XHR 请求并不是一种测试连接性的方法。考虑到其他答案之一指出 XHR 存在太多故障点,如果您的 XHR 在建立连接时存在缺陷,那么无论如何它在日常使用过程中也会存在缺陷。如果您的站点因任何原因无法访问,那么您在同一服务器上运行的其他服务也可能无法访问。这个决定取决于你。

I wouldn't recommend making an XHR request to someone else's service, even google.com for that matter. Make the request to your server, or not at all.

我不建议向其他人的服务提出 XHR 请求,即使是 google.com。向您的服务器发出请求,或者根本不发出请求。

What does it mean to be "online"?

“在线”是什么意思?

There seems to be some confusion around what being "online" means. Consider that the internet is a bunch of networks, however sometimes you're on a VPN, without access to the internet "at-large" or the world wide web. Often companies have their own networks which have limited connectivity to other external networks, therefore you could be considered "online". Being online only entails that you are connected to anetwork, not the availability nor reachability of the services you are trying to connect to.

关于“在线”的含义似乎有些混乱。考虑到互联网是一堆网络,但有时您使用的是 VPN,无法访问“一般”互联网或万维网。公司通常拥有自己的网络,但与其他外部网络的连接有限,因此您可以被视为“在线”。正在网上只需要你连接到一个网络,你试图连接到服务的不可用性也可达性。

To determine if a host is reachable from your network, you could do this:

要确定主机是否可以从您的网络访问,您可以执行以下操作:

function hostReachable() {

  // Handle IE and more capable browsers
  var xhr = new ( window.ActiveXObject || XMLHttpRequest )( "Microsoft.XMLHTTP" );

  // Open new request as a HEAD to the root hostname with a random param to bust the cache
  xhr.open( "HEAD", "//" + window.location.hostname + "/?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;
  }

}

You can also find the Gist for that here: https://gist.github.com/jpsilvashy/5725579

您还可以在此处找到 Gist:https: //gist.github.com/jpsilvashy/5725579

Details on local implementation

本地实施详情

Some people have commented, "I'm always being returned false". That's because you're probably testing it out on your local server. Whatever server you're making the request to, you'll need to be able to respond to the HEAD request, that of course can be changed to a GET if you want.

有些人评论说,“我总是被退回假”。那是因为您可能正在本地服务器上对其进行测试。无论您向哪个服务器发出请求,您都需要能够响应 HEAD 请求,如果您愿意,当然可以将其更改为 GET。

回答by morespace54

Ok, maybe a bit late in the game but what about checking with an online image? I mean, the OP needs to know if he needs to grab the Google CMD or the local JQ copy, but that doesn't mean the browser can't read Javascript no matter what, right?

好吧,也许游戏有点晚了,但是通过在线图像检查怎么样?我的意思是,OP 需要知道他是否需要获取 Google CMD 或本地 JQ 副本,但这并不意味着浏览器无论如何都无法读取 Javascript,对吧?

<script>
function doConnectFunction() {
// Grab the GOOGLE CMD
}
function doNotConnectFunction() {
// Grab the LOCAL JQ
}

var i = new Image();
i.onload = doConnectFunction;
i.onerror = doNotConnectFunction;
// CHANGE IMAGE URL TO ANY IMAGE YOU KNOW IS LIVE
i.src = 'http://gfx2.hotmail.com/mail/uxp/w4/m4/pr014/h/s7.png?d=' + escape(Date());
// escape(Date()) is necessary to override possibility of image coming from cache
</script>

Just my 2 cents

只是我的 2 美分

回答by Phil Rykoff

5 years later-version:

5年后版本:

Today, there are JS libraries for you, if you don't want to get into the nitty gritty of the different methods described on this page.

今天,有一些 JS 库适合您,如果您不想深入了解此页面上描述的不同方法的本质。

On of these is https://github.com/hubspot/offline. It checks for the connectivity of a pre-defined URI, by default your favicon. It automatically detects when the user's connectivity has been reestablished and provides neat events like upand down, which you can bind to in order to update your UI.

其中之一是https://github.com/hubspot/offline。它检查预定义 URI 的连接性,默认情况下是您的收藏夹图标。它会自动检测用户的连接何时重新建立,并提供诸如up和 之类的简洁事件down,您可以绑定到这些事件以更新您的 UI。

回答by Vitim.us

You can mimic the Ping command.

您可以模仿 Ping 命令。

Use Ajax to request a timestamp to your own server, define a timer using setTimeout to 5 seconds, if theres no response it try again.

使用 Ajax 向您自己的服务器请求时间戳,使用 setTimeout 定义一个计时器为 5 秒,如果没有响应则重试。

If there's no response in 4 attempts, you can suppose that internet is down.

如果 4 次尝试都没有响应,您可以认为互联网已关闭。

So you can check using this routine in regular intervals like 1 or 3 minutes.

因此,您可以定期检查使用此例程,例如 1 或 3 分钟。

That seems a good and clean solution for me.

这对我来说似乎是一个很好且干净的解决方案。

回答by Soufiane Hassou

You can try by sending XHR Requests a few times, and then if you get errors it means there's a problem with the internet connection.

您可以尝试多次发送 XHR 请求,然后如果出现错误,则表示 Internet 连接存在问题。

Edit:I found this JQuery scriptwhich is doing what you are asking for, I didn't test it though.

编辑:我发现这个 JQuery 脚本正在执行您的要求,但我没有对其进行测试。

回答by tripRev

I wrote a jQuery plugin for doing this. By default it checks the current URL (because that's already loaded once from the Web) or you can specify a URL to use as an argument. Always doing a request to Google isn't the best idea because it's blocked in different countries at different times. Also you might be at the mercy of what the connection across a particular ocean/weather front/political climate might be like that day.

我为此编写了一个 jQuery 插件。默认情况下,它会检查当前 URL(因为它已经从 Web 加载了一次),或者您可以指定一个 URL 以用作参数。总是向 Google 提出请求并不是最好的主意,因为它在不同的国家/地区在不同的时间被屏蔽。此外,您可能会受制于特定海洋/天气前沿/气候之间的联系可能会像那天一样。

http://tomriley.net/blog/archives/111

http://tomriley.net/blog/archives/111

回答by Mistermika

i have a solution who work here to check if internet connection exist :

我有一个在这里工作的解决方案来检查互联网连接是否存在:

$.ajax({
    url: "http://www.google.com",
    context: document.body,
    error: function(jqXHR, exception) {
        alert('Offline')
    },
    success: function() {
        alert('Online')
    }
})

回答by Mike Trpcic

Sending XHR requests is bad because it could fail if that particular server is down. Instead, use googles API library to load their cached version(s) of jQuery.

发送 XHR 请求很糟糕,因为如果该特定服务器关闭,它可能会失败。相反,使用 googles API 库来加载他们缓存的 jQuery 版本。

You can use googles API to perform a callback after loading jQuery, and this will check if jQuery was loaded successfully. Something like the code below should work:

加载 jQuery 后,您可以使用 googles API 执行回调,这将检查 jQuery 是否加载成功。像下面的代码应该工作:

<script type="text/javascript">
    google.load("jquery");

    // Call this function when the page has been loaded
    function test_connection() {
        if($){
            //jQuery WAS loaded.
        } else {
            //jQuery failed to load.  Grab the local copy.
        }
    }
    google.setOnLoadCallback(test_connection);
</script>

The google API documentation can be found here.

可以在此处找到 google API 文档。

回答by web site maker

A much simpler solution:

一个更简单的解决方案:

<script language="javascript" src="http://maps.google.com/maps/api/js?v=3.2&sensor=false"></script>

and later in the code:

然后在代码中:

var online;
// check whether this function works (online only)
try {
  var x = google.maps.MapTypeId.TERRAIN;
  online = true;
} catch (e) {
  online = false;
}
console.log(online);

When not online the google script will not be loaded thus resulting in an error where an exception will be thrown.

当不在线时,不会加载 google 脚本,从而导致将抛出异常的错误。