How to detect online/offline event cross-browser?

2019-01-02 17:32发布

I'm trying to accurately detect when the browser goes offline, using the HTML5 online and offline events.

Here's my code:

<script>
    // FIREFOX
    $(window).bind("online", applicationBackOnline); 
    $(window).bind("offline", applicationOffline);

    //IE
    window.onload = function() {
        document.body.ononline = IeConnectionEvent;
        document.body.onoffline = IeConnectionEvent;
    } 
</script>

It works fine when I just hit "Work offline" on either Firefox or IE, but it's kind of randomly working when I actually unplug the wire.

What's the best way to detect this change? I'd like to avoid repeating ajax calls with timeouts.

15条回答
忆尘夕之涩
2楼-- · 2019-01-02 18:04

well, you can try the javascript plugin which can monitor the browser connection in real time and notifies the user if internet or the browsers connection with the internet went down.

Wiremonkey Javascript plugin and the demo you can find here

http://ryvan-js.github.io/

查看更多
一个人的天荒地老
3楼-- · 2019-01-02 18:07

The window.navigator.onLine attribute and its associated events are currently unreliable on certain web browsers (especially Firefox desktop) as @Junto said, so I wrote a little function (using jQuery) that periodically check the network connectivity status and raise the appropriate offline and online event:

// Global variable somewhere in your app to replicate the 
// window.navigator.onLine variable (it is not modifiable). It prevents
// the offline and online events to be triggered if the network
// connectivity is not changed
var IS_ONLINE = true;

function checkNetwork() {
  $.ajax({
    // Empty file in the root of your public vhost
    url: '/networkcheck.txt',
    // We don't need to fetch the content (I think this can lower
    // the server's resources needed to send the HTTP response a bit)
    type: 'HEAD',
    cache: false, // Needed for HEAD HTTP requests
    timeout: 2000, // 2 seconds
    success: function() {
      if (!IS_ONLINE) { // If we were offline
        IS_ONLINE = true; // We are now online
        $(window).trigger('online'); // Raise the online event
      }
    },
    error: function(jqXHR) {
      if (jqXHR.status == 0 && IS_ONLINE) {
        // We were online and there is no more network connection
        IS_ONLINE = false; // We are now offline
        $(window).trigger('offline'); // Raise the offline event
      } else if (jqXHR.status != 0 && !IS_ONLINE) {
        // All other errors (404, 500, etc) means that the server responded,
        // which means that there are network connectivity
        IS_ONLINE = true; // We are now online
        $(window).trigger('online'); // Raise the online event
      }
    }
  });
}

You can use it like this:

// Hack to use the checkNetwork() function only on Firefox 
// (http://stackoverflow.com/questions/5698810/detect-firefox-browser-with-jquery/9238538#9238538)
// (But it may be too restrictive regarding other browser
// who does not properly support online / offline events)
if (!(window.mozInnerScreenX == null)) {
    window.setInterval(checkNetwork, 30000); // Check the network every 30 seconds
}

To listen to the offline and online events (with the help of jQuery):

$(window).bind('online offline', function(e) {
  if (!IS_ONLINE || !window.navigator.onLine) {
    alert('We have a situation here');
  } else {
    alert('Battlestation connected');
  }
});
查看更多
孤独寂梦人
4楼-- · 2019-01-02 18:09

I use the FALLBACK option in the HTML5 cache manifest to check if my html5 app is online or offline by:

FALLBACK:
/online.txt /offline.txt

In the html page i use javascript tot read the contents of the online/offline txt file:

<script>$.get( "urlto/online.txt", function( data ) {
$( ".result" ).html( data );
alert( data );
});</script>

When offline the script will read the contents of the offline.txt. Based on the text in the files you can detect if the webpage is online of offline.

查看更多
ら面具成の殇う
5楼-- · 2019-01-02 18:10

you can detect offline cross-browser way easily like below

var randomValue = Math.floor((1 + Math.random()) * 0x10000)

$.ajax({
      type: "HEAD",
      url: "http://yoururl.com?rand=" + randomValue,
      contentType: "application/json",
      error: function(response) { return response.status == 0; },
      success: function() { return true; }
   });

you can replace yoururl.com by document.location.pathname.

The crux of the solution is, try to connect to your domain name, if you are not able to connect - you are offline. works cross browser.

查看更多
时光乱了年华
6楼-- · 2019-01-02 18:14

Using Document Body:

<body ononline="onlineConditions()" onoffline="offlineConditions()">(...)</body>

Using Javascript Event:

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

  function updateOnlineStatus(event) {

    var condition = navigator.onLine ? "online" : "offline";
    if( condition == 'online' ){
        console.log( 'condition: online')
    }else{
        console.log( 'condition: offline')
    }

  }

  window.addEventListener('online',  updateOnlineStatus(event) );
  window.addEventListener('offline', updateOnlineStatus(event) );

});

Reference:
Document-Body: ononline Event
Javascript-Event: Online and offline events

Additional Thoughts:
To ship around the "network connection is not the same as internet connection" Problem from the above methods: You can check the internet connection once with ajax on the application start and configure an online/offline mode. Create a reconnect button for the user to go online. And add on each failed ajax request a function that kick the user back into the offline mode.

查看更多
怪性笑人.
7楼-- · 2019-01-02 18:14
登录 后发表回答