17

I have searched through StackOverflow and have seen various topics on how to do this, but nothing that really pertains to my particular situation. I am writing (for a class) a mobile "application" (using HTML5, CSS, jQuery). It will end up being a stand alone "app", something that will contain a local copy of all the needed files. On one of my pages I have a submit form, and since the user can't submit the form if they are offline, I would like the page to be redirected to a custom 404 page.

I was just searching to see if there was a way to accomplish this in jQuery, as I haven't really found anything yet.

Thanks

Brendan Lesniak
  • 2,271
  • 4
  • 24
  • 48

7 Answers7

23

You could use

if (navigator.onLine) {
    // I'm online so submit the form.
}
Bot
  • 11,868
  • 11
  • 75
  • 131
  • I tried as you specified; alerting inside both the if/else. The if works perfectly as I would expect, when I disable my network connection to test the else, it fails and still displays what would be shown in the if statement. – Brendan Lesniak Mar 02 '12 at 01:18
  • It isn't fool proof, it gets the data from the browser. – Bot Mar 02 '12 at 01:26
  • 1
    it just shows if you're in `Offline` mode or not, I was looking for a way to actually check if you have internet access or not. – Akbari Oct 27 '16 at 06:21
22

You actually don't need jQuery for this at all. HTML5 itself has a neat facility for applications ran in online/offline conditions - cache manifest. The cache manifest is a plain text file referenced in the manifest attribute of <html> tag:

<html manifest="cache.manifest">

The contents of this manifest file tells the browser, which resources need online conditions to function (NETWORK), which files to cache (CACHE) and what to do when network resource is requested while offline (FALLBACK).

CACHE MANIFEST
# the above line is required

NETWORK:
*

FALLBACK:
*   error404.html

CACHE:
index.html
about.html
help.html
# Plus all other resources required to make it look nice
style/default.css
images/logo.png
images/backgound.png

When using manifest, browser first consults the manifest and, without any scripting, acts accordingly based on being online or offline.

http://dev.w3.org/html5/spec-preview/offline.html#manifests

UPDATE:

Please note the crucial requirement on response content type. Plain text simply doesn't work.

Manifests must be served using the text/cache-manifest MIME type.

http://dev.w3.org/html5/spec-preview/offline.html#writing-cache-manifests

Also be aware that all URLs not listed in the manifest are blocked from load as a result. That's why I've fixed the above manifest with wildcards (*) to allow "the rest". That might help you get started.

Petr Vostrel
  • 2,324
  • 16
  • 23
  • Interesting....this could be what I was looking for...Assume I have 5 web pages (index.html, contact.html, about.html, rates.html, reserve.html), and the index will be displayed no matter what, along with the about page. Contact, reserve, and rates I want to link to the custom 404 page when I am offline; how would I do that? – Brendan Lesniak Mar 05 '12 at 20:11
  • I gave you the bounty, because even though I couldn't get your solution to work on my normal browser, I believe it is a good way to go if I was strictly coding for mobile. – Brendan Lesniak Mar 06 '12 at 03:23
  • @Brendan, cache manifests work on normal desktop browsers too and in the very same way. I've updated the answer again with common content type gotcha and since I've just recently discovered, that cache manifest essentially acts sort of like a firewall, to whom you must tell which network resources to actually allow, I've employed wildcards to allow all your resources, otherwise they'd be blocked. You just pick which one of them you'd like to cache and list it in the manifest. – Petr Vostrel Mar 06 '12 at 16:48
  • @vishwanath Just double checked and all three links and all do work. – Petr Vostrel Mar 30 '13 at 11:42
  • Oops, It does some redirection after some time, I didn't wait earlier for that much time. Thanks for your response.. – Vishwanath Mar 30 '13 at 13:10
  • +1 for the nice hint, but sorry, all 3 links indeed went broken by now (FYI @vishwanath, too). :-/ (Those guys at W3C don't quite seem to have mastered the skills of creating easy-to-use, robust web sites yet. ;-p ) – Sz. Mar 11 '14 at 14:43
  • Links fixed. Hopefully this new location will stay up for longer ;) - http://dev.w3.org/html5/spec-preview/offline.html – Petr Vostrel Mar 12 '14 at 01:58
17

You can either check the navigator.onLine property or listen to the offline/online events:

$(document).on('offline online', function (event) {
    alert('You are ' + event.type + '!');
});

Source: http://www.html5rocks.com/en/mobile/workingoffthegrid/

And here are some MDN docs for these events: https://developer.mozilla.org/en/Online_and_offline_events

I'm not familiar with these events myself, but if you read the above links, you should find a lot of good information.

Jasper
  • 75,717
  • 14
  • 151
  • 146
  • This looks like a clean way to do it, but do these events work in all browsers? – Todd Moses Mar 02 '12 at 01:23
  • 1
    Absolutely not :). This is using HTML5 specific events, which isn't an official spec yet. Here is a link to the MDN site for `navigator.onLine`: https://developer.mozilla.org/en/DOM/window.navigator.onLine (Browser support is at the bottom) – Jasper Mar 02 '12 at 01:29
  • 2
    @ToddMoses I would have to test it out to make sure it worked, but Todd Moses' answer seems like a good one to use. But you could use a small resource to load rather than a whole framework. For instance you can host your own JS file that just adds a flag to the global scope, if the flag exists then the user is online. To make sure the JS file isn't cached you'll have to properly set the headers for the file to always refresh. – Jasper Mar 02 '12 at 01:31
4

I'm using the following code to check for connectivity. NOTE: none of the solutions above work for Firefox, which relies on its internal 'Work Offline' status:

// Register listeners
window.addEventListener("offline", function(){
    $('#globalDiv').hide();
    $("#message").html('WARNING: Internet connection has been lost.').show();
});
window.addEventListener("online", function(){
    $("#message").empty().hide();
    $('#globalDiv').show();
});
  • As of 2015 this answer seems to be the most reliable if you want a simple event to use. – dlsso Nov 16 '15 at 17:17
  • how can I reinitialize this in every page when navigate through pages while no network connection. This is working but I need to allow navigation through pages whether there is no network. As well I need to show the no network message in every page. – WP Learner May 10 '16 at 08:25
  • 1
    You can display the "No network" message as a banner at the top of the page in stead of blocking the whole page, but allowing navigation while there,s no network is another topic. For that, you need to have your pages cached locally. HTML5 has a mechanism for that (cache manifest), please refer to this for reference: http://www.w3schools.com/html/html5_app_cache.asp – Webomatik May 15 '16 at 22:15
3

try to set up ajaxSetup to do a request every n milliseconds (i put 1000 here) and check if it times out and then disable button.

$.ajaxSetup({
    timeout: 1000, 
    error: function(request, status, maybe_an_exception_object) {
        if(status != 'timeout')
            //Code to enable button
        else
             //Code to disable button
    }
});
PraveenVenu
  • 8,217
  • 4
  • 30
  • 39
2

Using window.navigator.onLine is inherantly unreliable, because the user might be connected to a network, but that network could not have internet access.

However, here is a barebones example

<!DOCTYPE HTML>
<html>
 <head>
  <title>Online status</title>
  <script>
   function updateIndicator() {
     document.getElementById('indicator').textContent = navigator.onLine ? 'online' : 'offline';
   }
  </script>
 </head>
 <body onload="updateIndicator()" ononline="updateIndicator()" onoffline="updateIndicator()">
  <p>The network is: <span id="indicator">(state unknown)</span>
 </body>
</html>​

See the fiddle in action: http://jsfiddle.net/3rRWK/

Layke
  • 51,422
  • 11
  • 85
  • 111
0

Here is what I would do, based upon: how to check if the user has the connection to the internet

First, use a javascript library link to determine if user is online. If true change the action property of your form to the online page, else the offline page.

    <script src="https://ajax.googleapis.com/ajax/libs/prototype/1.7.0.0/prototype.js></script>
    <script>
$('#target').submit(function() {
   if (typeof window.$ !== 'function') {
    $('myform').attr( "action" , "offlinepage.html"  );
   }
   else
   {
    $('myform').attr( "action" , "onlinepage.html"  );
   }
});
    </script>
Community
  • 1
  • 1
Todd Moses
  • 10,969
  • 10
  • 47
  • 65