Remote update your Cordova App
A little later...
CordovaAppLoader
to
check()
for a new manifestdownload()
filesupdate()
your app!Check out Cordova App Loader in Chrome for a demo! (Chrome only!)
Or run on your own computer:
git clone git@github.com:markmarijnissen/cordova-app-loader.git
cd cordova-app-loader
cordova platform add ios@3.7.0
cordova plugin add cordova-plugin-file
cordova plugin add cordova-plugin-file-transfer
cordova run ios
All code is in the www
directory. Modify serverRoot
in www/app.js
to run your own server.
Check out autoupdate.js - it automatically updates when you open or resume the app.
Automatic updates have a few downsides:
Setup Cordova (see below)
Download to your www
directory:
Write a manifest.json (see below). Include autoupdate.js
and cordova-app-loader-complete.js
.
Set the correct server in index.html
:
<script
type="text/javascript"
server="http://data.madebymark.nl/cordova-app-loader/"
manifest="manifest.json"
src="https://github.com/markmarijnissen/cordova-app-loader/raw/master/bootstrap.js"></script>
Write window.BOOTSTRAP_OK = true
in your code when your app succesfully launches.
Launch your app.
Now you can remote update your app:
cordova platform add ios@3.7.0
cordova plugin add org.apache.cordova.file
cordova plugin add org.apache.cordova.file-transfer
cordova plugin add cordova-plugin-whitelist
IMPORTANT: For iOS, use Cordova 3.7.0 or higher (due to a bug that affects requestFileSystem).
For Android, the plugin cordova-plugin-whitelist
is needed. You must also add the following to your config.xml
file.
<access origin="cdvfile://*" />
<allow-intent href="https://github.com/markmarijnissen/cordova-app-loader/blob/master/cdvfile://*" />
You need bootstrap.js (github, file) to read the manifest.json to launch your app.
Add bootstrap.js to your index.html.
Option 1: Download all dependencies as a single pre-build file (easy)
Download cordova-app-loader-complete.js (github, download, minified). This build uses promiscuous (github,download) as Promise library.
Option 2: Download pre-build files for every module (customizable)
If you want to use your own Promise library, you have to load every module individually:
Option 3: Use Bower to fetch pre-build modules:
bower install cordova-app-loader
bower install cordova-promise-fs
bower install bluebird # or another library that follows the Promise/A+ spec.
Option 4: Use NPM to fetch CommonJS modules:
npm install cordova-app-loader
npm install cordova-promise-fs
npm install bluebird # or another library that follows the Promise/A+ spec.
Before you start, you need to write a manifest.json to describe:
{
"files": { // these files are downloaded
"cordova-app-loader-complete": {
"version": "76f1eecd3887e69d7b08c60be4f14f90069ca8b8",
"filename": "cordova-app-loader-complete.js"
},
"autoupdate": {
"version": "76f1eecd3887e69d7b08c60be4f14f90069ca8b8",
"filename": "autoupdate.js"
},
"template": {
"version": "3e70f2873de3d9c91e31271c1a59b32e8002ac23",
"filename": "template.html"
},
"app": {
"version": "8c99369a825644e68e21433d78ed8b396351cc7d",
"filename": "app.js"
},
"style": {
"version": "6e76f36f27bf29402a70c8adfee0f84b8a595973",
"filename": "style.css"
}
},
"load": [ // these files are loaded in your index.html
"cordova-app-loader-complete.js",
"autoupdate.js",
"app.js",
"style.css"
]
}
You can update your existing manifest like this:
node node_modules/cordova-app-loader/bin/update-manifest www www/manifest.json
node node_modules/cordova-app-loader/bin/update-manifest [root-directory] [manifest.json]
It will update the version of only changed files (with a hash of the content).
There is also a Gruntfile available.
new CordovaAppLoader()
check()
for updatesdownload()
new filesupdate()
to apply updateSee autoupdate.js for an example of check()
, download()
and update()
.
Add bootstrap.js to your index.html. This retrieves manifest.json and dynamically inserts JS/CSS to the current page.
<script type="text/javascript" timeout="5000" manifest="manifest.json" src="https://github.com/markmarijnissen/cordova-app-loader/raw/master/bootstrap.js"></script>
On the second run, the manifest.json is retrieved from localStorage.
Set window.BOOTSTRAP_OK
to true
when your app has succesfully launched.
If your app is updated and window.BOOTSTRAP_OK
is not true after timeout
milliseconds, the corrupt manifest in localStorage is destroyed, and the page will reload. This will revert the app back to the original manifest.
You should always bundle a manifest.json (+ files) in your app to make sure your app has a "factory default" to revert back to. (And to make sure your app works offline).
// When using NPM, require these first.
// When using bower or when you downloaded the files these are already available as global variables.
var CordovaPromiseFS = require('cordova-promise-fs');
var CordovaAppLoader = require('cordova-app-loader');
var Promise = require('bluebird');
// Initialize a FileSystem
var fs = new CordovaPromiseFS({
Promise: Promise
});
// Initialize a CordovaAppLoader
var loader = new CordovaAppLoader({
fs: fs,
serverRoot: 'http://data.madebymark.nl/cordova-app-loader/',
localRoot: 'app',
cacheBuster: true, // make sure we're not downloading cached files.
checkTimeout: 10000 // timeout for the "check" function - when you loose internet connection
});
// download manifest from: serverRoot+'manifest.json'
loader.check().then(function(updateAvailable) { ... })
// download from custom url
loader.check('http://yourserver.com/manifest.json').then( ... )
// or just check an actual Manifest object.
loader.check({ files: { ... } }).then( ... )
Implementation Note: Only file versions are compared! If you, for example, update manifest.load
then the promise will return false
!
loader.download(onprogress)
.then(function(manifest){ ... },function(failedDownloadUrlArray){ ... });
Note: When downloading, invalid files are deleted first. This invalidates the current manifest. Therefore, the current manifest is removed from localStorage. The app is reverted to "factory settings" (the manifest.json that comes bundled with the app).
This writes the new manifest to localStorage and reloads the page to bootstrap the updated app.
// write manifest to localStorage and reload page:
loader.update() // returns `true` when update can be applied
// write manifest to localStorage, but DO NOT reload page:
loader.update(false)
Implementation Note: CordovaAppLoader changes the manifest.root
to point to your file cache - otherwise the bootstrap script can't find the downloaded files!
With the demo app, you can test:
There are also unit tests (Chrome only!).
It includes unit tests for CordovaPromiseFS and CordovaFileCache.
I want CordovaAppLoader to be fast, responsive, flexible, reliable and safe. In order to do this, I've thought about everything that could destroy the app loader and fixed it.
First, I wanted to download 'index.html' to storage, then redirect the app to this new index.html.
This has a few problems:
cordova.js
and plugin javascript cannot be found. cordova.js
in the manifest because it is platform specific.Dynamically inserting CSS and JS allows you for almost the same freedom in updates, without all these problems.
loader.download()
for the second time, old downloads are aborted.When updating, copy files that are already bundled with the app. (Of course, only if the file version has not changed)
check
and download
return a promise. These promises should always resolve - i.e. don't wait forever for a "deviceready" or for a "manifest.json" AJAX call to return.
I am assuming the following promises resolve or reject:
requestFileSystem
CordovaPromiseFS methods:
fs.root.getFile
)fs.root.getDirectory
)getDirectory
)dirReader.readEntries
)fileEntry.remove
)filetransfer.download()
to resolve the promise)XHR-request to fetch manifest.json (Rejected after timeout)
As you see, most methods rely on the succes/error callbacks of native/Cordova methods.
Only for deviceready
and the XHR-request I've added timeouts to ensure a timely response.
When using check
: The XHR will timeout.
When using download
: I am assuming Cordova will invoke the error callback. The download has a few retry-attempts. If the connetion isn't restored before the last retry-attemt, the download will fail.
The only critical moment is during a download. Old files are removed while new files aren't fully downloaded yet. This makes the current manifest point to missing or corrupt files. Therefore, before downloading, the current manifest is destroyed.
If the app crashes during a download, it will restart using the original manifest.
BOOTSTRAP_OK
is not set to true
after a timeout, the app will destroy the current manifest and revert back to the original manifest.If for some reason the downloaded files cannot be found in the cache on the next check()
, CordovaAppLoader will indicate true
, meaning there are still files to be downloaded.
This is correct and intended behavior, as we expect all files to be in the cache when check()
returns false.
However, depending on how/when you call check()
, this could result in a never-ending loop in which the app attempts to download files, but for some reason, the never end up in the cache.
To avoid this pitfall, the following safeguard is implemented:
Whenever you call update()
, the manifest is written to localStorage twice:
manifest
update_attempt_manifest
When calling check()
, it compares the new manifest with update_attempt_manifest
. If they are the same, it means you've attempted this before, so check()
will return false.
All filenames and paths are normalized.
/
, Android throws a NullPointerExpception)See CordovaPromiseFS for more details.
Let me know if you find bugs. Report an issue!
The version on your remote server is the single source of truth.
Here is a flow chart:
Did the app detect an earlier update the remote server?
Yes - Your App downloaded the update and is now running from the FileCache.
No - Your App never detected an update and is uses the bundled files.
/www/
. For example when your entry point is /www/app/index.html
.#/
while updating.serverRoot
from Manifest.json (only if you set allowServerRootFromManifest
to true
).dist
folder to for all build filesConvert CommonJS to a browser-version:
npm install webpack -g
npm run-script prepublish
Feel free to contribute to this project in any way. The easiest way to support this project is by giving it a star.
© 2014 - Mark Marijnissen