Detect Offline/Online Status

We introduce a method for detecting when the web app is online or offline to the example htmljQueryOfflineManifestoBlog . Our strategy is to use the manifest file for detecting if our server is reachable or not. If our server is not reachable then our web app is offline.

We add the following rule in the FALLBACK section in the manifest file.

manifest.appcache
...
FALLBACK:
/ping /ping-offline.json

In the application we try to laod the resource /ping . If it succeds, the following JSON content is returned from the Sinatra server: "Online"

Otheriwse, if the browser if offline, the request falls back to the cached version /ping-offline.json that contains the JSON string: "Offline"

Since we are automatically generating the manifest file, we add the fallback rule to the Manifesto array:

server.rb
...
get '/manifest.appcache' do
  headers 'Content-Type' => 'text/cache-manifest' # Must be served with this MIME type
  cache_control :no_cache #Disable caching of manifest file, only for demo purposes
  Manifesto.cache << "FALLBACK:\n /ping /ping-offline.json\n"
end
get '/ping' do
  content_type :json
  "Online".to_json
end
...

We place the fallback file in the public directory

public/ping-offline.json
"Offline"

In the application, we add the JS logic for pinging our server every 10s and we show the status in the header.

views/header.haml
%div(data-role="header")
  %h1.status 
  %a(href="#options" data-icon="gear" class="ui-btn-right" data-transition="slidedown") Options
views/layout.haml
$(function() {
  function testOnline() {
    $.getJSON('ping', function(data) {
      $('.status').html(data);  
    });
  }

//Test at first page load
testOnline();

//Test a timer for infinite testing
window.setInterval(testOnline, 10000);

...

You can try this example by starting the server and visiting the page http://localhost:4567 in your browser

terminal
ruby server.rb