Hello HTML5 Offline Cache: NodeJS+Express Minimal Example

#!/usr/bin/env node

var Http=require('http');
var Express=require('express');
var Morgan=require('morgan');
require('date-format-lite');

var app = Express();
app.use(Morgan('combined'));

var version=1;

app.get('/cache.manifest',function(q,s){
    s.setHeader('content-type','text/cache-manifest');
    s.end(['CACHE MANIFEST','#v'+version,'CACHE:','/'].join("\n"));
});

app.get('/', function(q,s){
    var r=''
    r+='<html manifest="cache.manifest">';
    r+='<body>hello world,v'+version+'</body>';
    r+='</html>';
    s.end(r);
});

Http.createServer(app).listen(8080);

Actual application design

Example

window.addEventListener('load', function(e) {
    window.applicationCache.addEventListener('updateready', function(e) {
        window.applicationCache.swapCache();
        window.location.reload();
    })
    window.applicationCache.update();
})

Safari (MacOSX/iOS-iPhone) behavior (Tested version:iOS8)

Chrome behavior (Tested version:38.0.2125.111)

How to use cache.manifest with Client Certification on Safari

Safari fails loading cache.manifest or pages to be cached which needed Client Certification(Bug?). If you want to use cache.manifest on HTTPS with rejectUnauthorized:true, Bypassing authentication when accessing cache.manifest or pages which allowed caching is necessary. Refer following example.

var app = Express();
.
.
//Bypass authentication of manifest file and pages for cache
app.use(function(q,s,next){
    var whiteList=['/cache.manifest','/cached.html'];
    if(q.client.authorized||whiteList.indexOf(q.url)>=0){
        next()    //Authorize by cookie (such as express-session) for white list urls at this point.
    }else{
        s.status(404).end();
    }
})

var httpsOptions={
    key: Fs.readFileSync(Path.join(__dirname,'self-private-key.pem')),
    cert: Fs.readFileSync(Path.join(__dirname,'self-certificate.pem')),
    ca: [ Fs.readFileSync(Path.join(__dirname,'ca-certificate.pem')) ],
    requestCert:true,
    rejectUnauthorized:false   //Disable automatic authentication checking.
}

Https.createServer(httpsOptions,app).listen(app.get('port'))

Popular Articles from This Page

Top Page

Economizing Technology > Hello HTML5 Offline Cache: NodeJS+Express Minimal Example