Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if connected to a network; jQuery

Tags:

html

jquery

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

like image 891
Brendan Lesniak Avatar asked Mar 02 '12 01:03

Brendan Lesniak


2 Answers

You could use

if (navigator.onLine) {
    // I'm online so submit the form.
}
like image 111
Bot Avatar answered Sep 28 '22 16:09

Bot


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.

like image 43
Petr Vostrel Avatar answered Sep 28 '22 16:09

Petr Vostrel