javascript 如何使用javascript或任何库检查用户是否在线?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/29802403/
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-10-28 11:06:09  来源:igfitidea点击:

How to check if the user is online using javascript or any library?

javascriptjqueryoffline

提问by Stranger B.

I need some help on how I could check the internet connection using Javascriptor jQueryor any library if available. cause i'm developing an offline application and I want to show a version if the user is offline and another version if the user is online.

我需要一些关于如何使用JavascriptjQuery或任何可用库检查互联网连接的帮助。因为我正在开发一个离线应用程序,如果用户离线,我想显示一个版本,如果用户在线,我想显示另一个版本。

For the moment i'm using this code :

目前我正在使用此代码:

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

But this is working very slow to detect. sometimes it's just connected to a network without internet, it takes 5 to 10 seconds to alert false(No internet).

但这很难检测到。有时它只是连接到没有互联网的网络,需要 5 到 10 秒才能发出警报false(没有互联网)。

I took a look at Offline.js library, but I'm not sure if this library is useful in my case. and I don't know how to use it

我查看了 Offline.js 库,但我不确定这个库是否对我有用。我不知道如何使用它

回答by Jamie Barker

I just got this bit of code functionality from a Mozilla Site:

我刚刚从Mozilla 站点获得了一些代码功能:

window.addEventListener('load', function(e) {
  if (navigator.onLine) {
    console.log('We\'re online!');
  } else {
    console.log('We\'re offline...');
  }
}, false);

window.addEventListener('online', function(e) {
  console.log('And we\'re back :).');
}, false);

window.addEventListener('offline', function(e) {
  console.log('Connection is down.');
}, false);

They even have a link to see it working. I tried it in IE, Firefox and Chrome. Chrome appeared the slowest but it was only about half a second.

他们甚至有一个链接可以查看它的工作情况。我在 IE、Firefox 和 Chrome 中尝试过。Chrome 看起来最慢,但它只有大约半秒。

回答by Doml The-Bread

i think you should try OFFLINE.js.. it looks pretty easy to use, just give it a try.

我认为你应该尝试OFFLINE.js.. 它看起来很容易使用,试试吧。

it even provides the option checkOnLoadwhich checks the connection immediately on page load.

它甚至提供了checkOnLoad在页面加载时立即检查连接的选项。

Offline.check(): Check the current status of the connection.

Offline.state: The current state of the connection 'up' or 'down'

Offline.check():检查连接的当前状态。

Offline.state:连接'up'或'down'的当前状态

haven't tried it, would be nice to know if it works as intended.

还没有尝试过,很高兴知道它是否按预期工作。

EDITtook a little peak into the code, it uses the method with FAILED XHR REQUESTsuggested in THISSO Question

编辑在代码中占据了一个小高峰,它使用了在这个问题中建议的FAILED XHR REQUEST的方法

回答by dmeglio

Take a look at Detect that the Internet connection is offline?Basically, make an ajax request to something you know is likely to be up (say google.com) and if it fails, there is no internet connection.

看看检测互联网连接是否离线?基本上,向您知道可能会启动的内容(例如 google.com)发出 ajax 请求,如果失败,则表示没有互联网连接。

回答by guest271314

Try utilizing WebRTC, see diafygi/webrtc-ips; in part

尝试使用WebRTC,参见diafygi/webrtc-ips;部分

Additionally, these STUN requests are made outside of the normal XMLHttpRequest procedure, so they are not visible in the developer console or able to be blocked by plugins such as AdBlockPlus or Ghostery. This makes these types of requests available for online tracking if an advertiser sets up a STUN server with a wildcard domain.

此外,这些 STUN 请求是在正常的 XMLHttpRequest 过程之外发出的,因此它们在开发人员控制台中不可见,或者能够被 AdBlockPlus 或 Ghostery 等插件阻止。如果广告商使用通配符域设置 STUN 服务器,这将使这些类型的请求可用于在线跟踪。



modified minimally to log "online" or "offline" at console

最低限度地修改以在以下位置记录“在线”或“离线” console

// https://github.com/diafygi/webrtc-ips
function online(callback){

    //compatibility for firefox and chrome
    var RTCPeerConnection = window.RTCPeerConnection
        || window.mozRTCPeerConnection
        || window.webkitRTCPeerConnection;
    var useWebKit = !!window.webkitRTCPeerConnection;

    //bypass naive webrtc blocking using an iframe
    if(!RTCPeerConnection) {
        //NOTE: you need to have an iframe in the page
        // right above the script tag
        //
        //<iframe id="iframe" sandbox="allow-same-origin" style="display: none"></iframe>
        //<script>...getIPs called in here...
        //
        var win = iframe.contentWindow;
        RTCPeerConnection = win.RTCPeerConnection
            || win.mozRTCPeerConnection
            || win.webkitRTCPeerConnection;
        useWebKit = !!win.webkitRTCPeerConnection;
    }

    //minimal requirements for data connection
    var mediaConstraints = {
        optional: [{RtpDataChannels: true}]
    };

    //firefox already has a default stun server in about:config
    //    media.peerconnection.default_iceservers =
    //    [{"url": "stun:stun.services.mozilla.com"}]
    var servers = undefined;

    //add same stun server for chrome
    if(useWebKit)
        servers = {iceServers: [{urls: "stun:stun.services.mozilla.com"}]};

    //construct a new RTCPeerConnection
    var pc = new RTCPeerConnection(servers, mediaConstraints);

    //create a bogus data channel
    pc.createDataChannel("");

    var fn = function() {};

    //create an offer sdp
    pc.createOffer(function(result){

        //trigger the stun server request
        pc.setLocalDescription(result, fn, fn);

    }, fn);

    //wait for a while to let everything done
    setTimeout(function(){
        //read candidate info from local description
        var lines = pc.localDescription.sdp.split("\n");
        // return `true`:"online" , or `false`:"offline"
        var res = lines.some(function(line) {
          return line.indexOf("a=candidate") === 0
        });
        callback(res);
    }, 500);
}

//Test: Print "online" or "offline" into the console
online(function(connection) {
  if (connection) {
    console.log("online")
  } else {
    console.log("offline")
  }
});

回答by CONvid19

My solution is to grab a very small image(1x1), not cachedand always onLine.

我的解决方案是抓取一个非常小的图像(1x1),不缓存并且始终在线

<head>
<script src="jquery.min.js"></script>
</head>
<body>
<script>
$( document ).ready(function() {
function onLine() {
alert("onLine")
}
function offLine() {
alert("offLine")
}
var i = new Image();
i.onload = onLine;
i.onerror = offLine;
i.src = 'http://www.google-analytics.com/__utm.gif';
});
</script>
<body>


Notes:

笔记:

  • Use a local copyof jQueryotherwise it won't work offLine.

  • I've tested the code onLine/offLineand it works without delay.

  • Works with all browsers, Desktop or Mobile.

  • In case you wonder, there's no tracking made from Google Analytics as we don't use any arguments.

  • Feel free to change the image, just make sure it doesn't get cached and it's small in size.

  • 使用 的本地副本jQuery否则它不会离线工作。

  • 我已经测试了代码onLine/offLine,它可以毫不延迟地工作

  • 适用于所有浏览器,桌面或移动。

  • 如果您想知道,由于我们不使用任何参数,因此不会从 Google Analytics 进行跟踪。

  • 随意更改图像,只需确保它不会被缓存并且尺寸很小。

回答by Selva kumar

navigator.onLine is a property that maintains a true/false value (true for online, false for offline). This property is updated whenever the user switches into "Offline Mode".

navigator.onLine 是一个保持真/假值的属性(在线时为真,离线时为假)。每当用户切换到“离线模式”时,此属性就会更新。

window.addEventListener('load', function() {

  function updateOnlineStatus(event) {
     document.body.setAttribute("data-online", navigator.onLine);
  }
  updateOnlineStatus();
  window.addEventListener('online',  updateOnlineStatus);
  window.addEventListener('offline', updateOnlineStatus);
});

回答by falsarella

You can use the new Fetch APIwhich will trigger an error almost immediately if no network is present.

您可以使用新的Fetch API,如果没有网络,它几乎会立即触发错误。

The problem with this is that the Fetch API has infant supportat the moment (currently Chrome has the most stable implementation, Firefox and Opera is getting there, IE does not support it). There exists a polyfillto support the fetch principle but not necessarily the rapid return as with a pure implementation. On the other hand, an offline app would require a modern browser...

问题在于 Fetch API目前尚不支持(目前 Chrome 拥有最稳定的实现,Firefox 和 Opera 正在实现,IE 不支持)。存在一个polyfill来支持 fetch 原则,但不一定像纯实现那样快速返回。另一方面,离线应用程序需要现代浏览器......

An example which will try to load a plain text file over HTTPS to avoid CORS requirements (link is picked at random, you should set up a server with a tiny text file to test against - test in Chrome, for now):

一个尝试通过 HTTPS 加载纯文本文件以避免 CORS 要求的示例(随机选择链接,您应该设置一个带有小文本文件的服务器进行测试 - 现在在 Chrome 中测试):

fetch("https://link.to/some/testfile")
    .then(function(response) {
        if (response.status !== 200) {  // add more checks here, ie. 30x etc.
            alert("Not available");     // could be server errors
        }
        else
            alert("OK");
    })
    .catch(function(err) {
        alert("No network");           // likely network errors (incl. no connection)
    });

Another option is to set up a Service workerand use fetch from there. This way you could serve an optional/custom offline page or a cached page when the requested page is not available. Also this is a very fresh API.

另一种选择是设置一个Service Worker并从那里使用 fetch。通过这种方式,您可以在请求的页面不可用时提供可选/自定义离线页面或缓存页面。这也是一个非常新鲜的 API。

回答by Justin Russo

You can use SignalR, if you're developing using MS web technologies. SignalR will establish either long polling or web sockets depending on your server/client browser technology, transparent to you the developer. You don't need to use it for anything else than determining if you have an active connection to the site or not.

如果您使用 MS Web 技术进行开发,则可以使用 SignalR。SignalR 将根据您的服务器/客户端浏览器技术建立长轮询或 Web 套接字,对开发人员来说是透明的。除了确定您是否有与该站点的活动连接之外,您不需要将它用于其他任何事情。

If SignalR disconnects for any reason, then you have lost connection to the site, as long as your SignalR server instance is actually installed on the site. Thus, you can use $.connection.hub.disconnected() event/method on the client to set a global var which holds your connection status.

如果 SignalR 因任何原因断开连接,那么只要您的 SignalR 服务器实例实际安装在站点上,您就会失去与站点的连接。因此,您可以在客户端上使用 $.connection.hub.disconnected() 事件/方法来设置保存连接状态的全局变量。

Read up about SignalR and how to use it for determining connection states here... http://www.asp.net/signalr/overview/guide-to-the-api/handling-connection-lifetime-events#clientdisconnect

在此处阅读有关 SignalR 以及如何使用它来确定连接状态的信息... http://www.asp.net/signalr/overview/guide-to-the-api/handling-connection-lifetime-events#clientdisconnect

回答by Teo Dragovic

// check if online/offline
// http://www.kirupa.com/html5/check_if_internet_connection_exists_in_javascript.htm
function doesConnectionExist() {
    var xhr = new XMLHttpRequest();
    var file = "http://www.yoursite.com/somefile.png";
    var randomNum = Math.round(Math.random() * 10000);

    xhr.open('HEAD', file + "?rand=" + randomNum, false);

    try {
        xhr.send();

        if (xhr.status >= 200 && xhr.status < 304) {
            return true;
        } else {
            return false;
        }
    } catch (e) {
        return false;
    }
}