Please note, this is a STATIC archive of website developer.mozilla.org from 03 Nov 2016, cach3.com does not collect or store any user information, there is no "phishing" involved.

Gather and modify data

Open web apps can access data stored or exposed by a device including files, the device hardware and services, the device location and orientation. By retrieving such numerous data, together with accessing third-party services, you can add cutting-edge features to your app such as real-time communication, synchronization, monitoring, making your app location-aware and responding to light conditions or new kinds of gestures.

This article provides recommendations for building web apps that interact with the hosting device, the tools to implement the most common use cases, along with FAQs, tutorials and real-world examples for anyone needing more detailed information on how to use APIs like the Geolocation API, the Orientation API and more.

Gathering data workflow

The following flowchart illustrates the typical workflow for retrieving data from the device hosting an open web app:

Every time the app is launched it retrieves the data needed for a specific feature (the device location for example), shows or stores the data (the current position on a map for example) and monitors data for changes so that it can be up-to-date.

Recommendations

The following is a set of recommendations and best practices for implementing features that require data from the device hardware, device services or third party services. These features include:

  • Real-time communication (WebRTC)
  • Synchronization (of contacts based on network speed for example)
  • Monitoring (of battery status for example)
  • Making your app location aware (using geolocation data)
  • Responding to light conditions (for e-book reader apps for example)
  • Handling new kinds of gesture (for games and other apps)

Gathering data

The Web Platform provides a set of APIs known as WebAPIs, with which open web apps can access data from device hardware or services.

Battery level and other useful information about the battery of the device hosting the application are provided by the Battery Status API. To access data provided by sensors such as the accelerometer, gyroscope and compass, you can use the Device Orientation API. In order to make your application location aware you can use the Geolocation API. You can even access camera and microphone (Navigator.getUserMedia), know the level of ambient light (Ambient Light Sensor API), and detect if an object is nearer to the device (Proximity API).

Each API provides JavaScript objects and events to developers. The following example shows how the navigator.geolocation JavaScript Object, part of the Geolocation API, that is used to get the current geoposition by a Web App.

var GeolocationManager = {
    /*
    * getCurrentPosition
    * Gets the current position of the device
    * @param {Function} successCallback
    * @param {Function} errorCallback
    * @param {PositionOptions} positionOptions
    */
    getCurrentPosition: function(successCallback, errorCallback, positionOptions) {

       /* If the geolocation object exists in navigator, get the current position of the device */
       if (navigator.geolocation) {
           navigator.geolocation.getCurrentPosition(successCallback, errorCallback, positionOptions);
       }
       else { // if the geolocation API is not supported
           errorCallback();
       }
    }
};

Note: Even though these APIs are JavaScript APIs, data is sometimes retrieved through HTML elements (in HTML Media Capture for example) or CSS Media Queries (in the Screen Orientation API for example).

Through JavaScript you can also hook into the contact database (Contacts API), the native file system (FileHandle API) or the filesystem within a web app (Device Storage API), check the network state (Network Information API) and even trigger Firefox OS actions such as “pick an image”, “send an e-mail”, etc. (Web Activities).

A complete list of the mentioned APIs are listed in the Reference section below. Each API has different level of support: some of them are well supported among browsers, some need prefixes to work, some work only on Firefox, and some need a Firefox OS App with a specified level of permission. Have a look at the browser compatibility table at the bottom of each MDN documentation page before starting to use an API in your app. If you find out that the API you want to use is not supported well enough across browsers, consider using non-stardard APIs provided by libraries such as Cordova.

Note: Open Web Apps can also gather data from third-party services exposing a REST API or RSS Feed for example.

Rendering your app

Retrieved data can be combined with other kinds of data, stored in the device or used to calculate or render something. Examples include a Google Map rendered through the Google Maps API, or the home screen of a weather app rendered through Yahoo! Weather RSS Feed. Moreover, data retrieved from device hardware and services can be sent to third-party services for server-side operations, for example to send a tweet through the Twitter REST API.

The code below shows how the Google Maps API is used to render the position retrieved by the getCurrentPosition function: the showPosition function is the successCallback of the example shown in the Gather Data section above.

/*
* showPosition
* Show the specified position on the map
* @param {Position} position
*/
showPosition: function(position) {

    /* Retrieve latitude and longitude from Position */
    var plat = position.coords.latitude;
    var plon = position.coords.longitude;
    
    /* Calculate the Google Maps position */
    var gmPosition = new google.maps.LatLng(plat, plon);
    
    /* Set the center of the map */
    this.map.setCenter(gmPosition);
}

Note: We would recommend using Object Oriented Programming when rendering your app, in order to make the code reusable.

Monitoring Data for changes

Changes in data can be detected via JavaScript events or CSS media queries.

The following example shows how changes in the battery status are monitored in order to update the status bar.

/* Update the battery status bar when the battery status changes */
EnergyManager.handleChangeEvents(BatteryStatusBar.update);

where EnergyManager and BatteryStatusBar are JavaScript objects defined by the application, and the handleChangeEvents method is defined as follows:

/*
* handleChangeEvents
* Registers an handler to every *-change events of navigator.battery
* @param {function} handler
* @returns {undefined}
*/
handleChangeEvents: function(handler) {

    /* Update the battery status bar on battery level change */
    navigator.battery.onlevelchange = function(e) {
       handler(e);
    };
    
    /* Update the battery status bar on battery charging change */
    navigator.battery.onchargingchange = function(e) {
       handler(e);
    };
    
    /* Update the battery status bar on battery charging time change */
    navigator.battery.onchargingtimechange = function(e) {
       handler(e);
    };
    
    /* Update the battery status bar on battery discharging time change */
    navigator.battery.ondischargingtimechange = function(e) {
       handler(e);
    };
}

Note: Not every API fires events to handle changes in data: for example the Geolocation API provides the Geolocation.watchPosition method, used to register a handler function that will be called automatically each time the position of the device changes.

Updating rendering

When data changes, the app needs to update the rendered view: depending on the app, the rendered view can be updated by refreshing the page, manipulating the DOM, or through an Ajax call if the updated data needs an interaction with the server-side app.

The following example shows how a battery status indicator gets updated by manipulating the DOM.

/*
* updateBatteryStatus
* Updates the battery status bar.
* @param {Event} event
* @returns {undefined}
*/
update: function(event) {

   /* Level */
   var percentage = EnergyManager.getBatteryPercentage();

   /* Color */
   if (percentage < 20) {
       this.batteryLevelDomObj.setAttribute('class', 'low level');
   }
   else if (percentage < 60) {
       this.batteryLevelDomObj.setAttribute('class', 'medium level');
   }
   else {
       this.batteryLevelDomObj.setAttribute('class', 'high level');
   }
}

What kind of data do you want to collect?

The data you want to collect can be retrieved from the device hardware, device services or third-party services. Depending on the data you want to collect you might have to use a specific Javascript API, CSS Media Feature, HTML element or attribute, RSS Feed or something else.

This section gives a bigger picture of these tools and provides examples, references and compatibility information.

From the device hardware

Location

JS API Name Gather data Monitor changes
Geolocation API

navigator.geolocation
.getCurrentPosition()

navigator.geolocation
.watchPosition()

 
Examples and tutorials
 
Reference and compatibility
 

Orientation

CSS Media Feature Gather data and monitor changes
orientation media feature @media orientation
JS API Name Gather data Modify data Monitor changes
orientation media feature screen.orientation screen.lockOrientation()
screen.unlockOrientation()
screen
.onorientationchange
JS API Name Gather data and monitor changes
Device Orientation API window.ondeviceorientation
Examples and tutorials
 
Reference and compatibility

Motion

JS API Name Gather data and monitor changes
Device Orientation API window.ondevicemotion
Examples and tutorials
 
Reference and compatibility
 

Ambient

JS API Name Gather data and monitor changes
Ambient Light API window.ondevicelight
window.onlightlevel
Examples and tutorials
 
Reference and compatibility
 

Battery

JS API Name Gather data Monitoring changes
Battery Status API

navigator.battery.level
navigator.battery.charging
navigator.battery.chargingTime
navigator.battery.dischargingTime

navigator.battery.onlevelchange
navigator.battery.onchargingchange
navigator.battery.onchargingtimechange
navigator.battery.ondischargingtimechange

Examples and tutorials
 
Reference and compatibility
 

Camera

HTML attribute Gather data
capture <input capture />
JS API Name Gather data
getUserMedia navigator.getUserMedia()
JS API Name Gather data
Camera API navigator.mozCameras.getCamera()
navigator.mozCameras.getListOfCameras()
Examples and tutorials
 
Reference and compatibility
 

Proximity

JS API Name Gather data and monitor changes
Proximity API window.ondeviceproximity
window.onuserproximity
Examples and tutorials
 
Reference and compatibility
 

From device services

Network

JS API Name Gather data Monitor changes
Network Information API navigator.connection.type navigator.connection.onchange
Examples and tutorials
 
Reference and compatibility
 

Contacts

JS API Name Gather data Monitor changes
Contacts API navigator.mozContacts mozContact.oncontactchange
Examples and tutorials
 
Reference and compatibility
 

Files

JS API Name Gather and modify data
FileHandle API window.indexedDB
Reference and compatibility
 

Storage

JS API Name Gather and modify data
Device Storage API navigator.getDeviceStorage()
Reference and compatibility
 

Firefox OS Services

JS API Name Gather and modify data
Web Activities new MozActivity()
Examples and tutorials
 
Reference and compatibility
 

From third party services

Twitter

JS API Name Gather data Modify data Monitor changes
Twitter REST API GET search/tweets POST statuses/update GET statuses/user_timeline
Examples and tutorials
 

Weather

RSS Feed Name Gather data and monitor changes
Yahoo Weather RSS Feed https://weather.yahooapis.com/forecastrss?w=location
Examples and tutorials
 

Examples

Responding to light conditions with the Ambient Light API
Ambient light sensors detect the presence and intensity of visible light. If used in a smart way, ambient light sensing optimizes visibility and battery life of portable devices such as tablets, smartphones, and laptops. This article looks at one way to respond to light conditions in the context of Open Web Apps: The Ambient Light API. Using this we can get information on the ambient light level and take actions to improve readability or create special effects depending on light conditions.
Retrieving battery status information via the Battery Status API
This article deconstructs a web application — the Low Energy Messenger — which uses battery status information to turn off high energy functions such as taking pictures when the device's battery is low. This presents a valid real world use case for the Battery Status API, plus an object-oriented JavaScript structure for handling the battery status functions.
Plotting yourself on the map
The Geolocation API, along with services such as Google Maps and OpenStreetMap, provides a great way to gather data about the user's surroundings — where they are, and what they can find nearby. This article gives a detailed account of how to build up a Geolocation application.
Keep it level: responding to device orientation changes
This article explores motion and orientation sensors (detecting when the device is tilted in different directions, for example) and associated W3C specifications, and explains how to makes use of such data in an HTML5 game written for the open web and Firefox OS devices.
Near or far? Responding to proximity
This article explains how the web platform can access the proximity sensors installed on mobile devices and provides an instant messaging and calls demo application that makes use of the Proximity API.
Optimizing for high and low network speeds
Network connectivity is a big issue for mobile apps, and network usage has many costs associated with it: battery life, performance and in some cases actual data transfer costs. These aspects should always be considered when designing and building cross platform Web Apps. This article explores a technology that facilitates optimization for high and low network speeds in the context of Open Web Apps: The Network Information API.
Updating phone contacts from the Web
Open web apps can benefit from integrating with the address books of devices they are installed on, especially on mobile devices in which contacts can be combined usefully with other data such as geolocation for personalised user experiences. This article explains how to build a real-world Firefox OS app that makes use of the API involved in managing phone contacts: the Contacts API.
Creating the Area Tweet app
This article shows how to gather data from third-party services exposing a REST API, the Twitter REST API, to build an app that can show and send tweets, and geolocating the user through the Geolocation API.
Weather app tutorial
This article shows how to gather data from third-party services exposing a RSS Feed, the Yahoo! Weather RSS Feed, to build an app providing information and forecast about the weather.

Tutorials

Reference

Document Tags and Contributors

 Contributors to this page: chrisdavidmills, xfq, HarishRamesh1993, franciov, FredB
 Last updated by: chrisdavidmills,