Les Open Web apps donnent aux développeurs web ce qu'ils ont attendu pendant des années: un environnement multi-plateforme dédié aux applications installables créées avec HTML, CSS et JavaScript - avec Firefox OS qui est la première plate-forme ouverte dédiée aux applications web. Ce guide vous permet de démarrer rapidement avec une architecture de base ainsi que les premières instructions. Vous pourrez ainsi créer la prochaine application révolutionnaire!
Si vous souhaitez suivre ce guide, vous pouvez télécharger nos modèles d'applications de démarrage rapide. Vous trouverez plus d'informations à propos de ce dernier en lisant notre guide sur les modèles d'applications.
Structure de l'application
Packaged vs. Hosted Apps
Il y a deux types d'applications web : packaged(empaquetées)
et hosted(hébergées)
. Les applications empaquetées sont essentiellement des fichiers zip
contenant toutes les ressources de l'application : HTML, CSS, JavaScript, images, manifeste, etc. Les applications hébergées sont exécutées à partir d'un serveur avec un domaine donné, comme les sites web standards. Les deux types d'application nécessitent un manifeste valide. Quand vous êtes prêt à soumettre votre application au Firefox Marketplace, vous devrez soit uploader votre application sous forme de zip, soit fournir l'URL où votre application est hébergée.
Pour les besoins de ce tutoriel, vous allez créer une application qui sera hébergée sur votre adresse localhost
. Une fois votre application prête à être postée dans le Firefox Marketplace, vous pourrez choisir la forme que prendra votre application : packaged app ou hosted app.
App Manifests
Chaque application Firefox requiert un fichier manifest.webapp dans l'application racine. Le fichier manifest.webapp
produit d'importantes informations sur l'application, comme la version, le nom, la description, les logos, les chaines locales, les domaines auquels l'application peut être installé, et beaucoup d'autres. Seulement le nom et la description sont requis.Le simple manifest inclus dans les modéles d'application est similaire a celui ci-dessous:
{ "version": "0.1", "name": "Open Web App", "description": "Your new awesome Open Web App", "launch_path": "/app-template/index.html", "icons": { "16": "/app-template/app-icons/icon-16.png", "48": "/app-template/app-icons/icon-48.png", "128": "/app-template/app-icons/icon-128.png" }, "developer": { "name": "Your Name", "url": "https://yourawesomeapp.com" }, "locales": { "es": { "description": "Su nueva aplicación impresionante Open Web", "developer": { "url": "https://yourawesomeapp.com" } }, "it": { "description": "Il vostro nuovo fantastico Open Web App", "developer": { "url": "https://yourawesomeapp.com" } } }, "default_locale": "en" }
Un manifest basique est tout dont tu as besoin pour commencer. Pour olus de détails a propos des manifests, lire App Manifest.
App Layout & Design
Le Responsive design est devenu de plus en plus important comme plusieurs resolutions d'ecrans deviennent des standards sur différents appareils. Même si le principal objectif de ton application sont les platformes mobiles comme Firefox OS, d'autres appareils auront probablement acces a ca. CSS media queries t'autorise a l'adapter selon la disposition de ton appareils, comme on le montre dans ce petit example CSS:
/* The following are examples of different CSS media queries */ /* Basic desktop/screen width sniff */ @media only screen and (min-width : 1224px) { /* styles */ } /* Traditional iPhone width */ @media only screen and (-webkit-min-device-pixel-ratio : 1.5), only screen and (min-device-pixel-ratio : 1.5) { /* styles */ } /* Device settings at different orientations */ @media screen and (orientation:portrait) { /* styles */ } @media screen and (orientation:landscape) { /* styles */ }
Il ya beaucoup de Frameworks JavaScript et CSS frameworks disponible pour t'aider dans le responsive design et dans le development d'application mobile (Bootstrap, etc.) Choisis le/les framework(s) qui est le mieux adapté a ton application et ton style de developpement.
Web APIs
Des APIs JavaScript ont été créés and augmentés rapidement comme les appareils. Mozilla's WebAPI effort brings dozens of standard mobile features to JavaScript APIs. A list of device support and status is available on the WebAPI page. JavaScript feature detection is still the best practice, as shown in the following example:
// If this device supports the vibrate API... if('vibrate' in navigator) { // ... vibrate for a second navigator.vibrate(1000); }
In the following example, the display style of a <div>
is modified based on changes in the battery state of the device:
// Create the battery indicator listeners (function() { var battery = navigator.battery || navigator.mozBattery || navigator.webkitBattery, indicator, indicatorPercentage; if(battery) { indicator = document.getElementById('indicator'), indicatorPercentage = document.getElementById('indicator-percentage'); // Set listeners for changes battery.addEventListener('chargingchange', updateBattery); battery.addEventListener('levelchange', updateBattery); // Update immediately updateBattery(); } function updateBattery() { // Update percentage width and text var level = (battery.level * 100) + '%'; indicatorPercentage.style.width = level; indicatorPercentage.innerHTML = 'Battery: ' + level; // Update charging status indicator.className = battery.charging ? 'charging' : ''; } })();
In the code sample above, once you confirm that the Battery API is supported, you can add event listeners for chargingchange
and levelchange
to update the element's display. Try adding the following to the quickstart template, and see if you can get it working.
Check the WebAPI page frequently to keep up to date with device API statuses.
Install API functionality
In our sample quickstart app template, we've implemented an install button that you can click when viewing the app as a standard Web page, to install that site on Firefox OS as an app. The button markup is nothing special:
<button id="install-btn">Install app</button>
This button's functionality is implemented using the Install API (see install.js):
var manifest_url = location.href + 'manifest.webapp'; function install(ev) { ev.preventDefault(); // define the manifest URL // install the app var installLocFind = navigator.mozApps.install(manifest_url); installLocFind.onsuccess = function(data) { // App is installed, do something }; installLocFind.onerror = function() { // App wasn't installed, info is in // installapp.error.name alert(installLocFind.error.name); }; }; // get a reference to the button and call install() on click if the app isn't already installed. If it is, hide the button. var button = document.getElementById('install-btn'); var installCheck = navigator.mozApps.checkInstalled(manifest_url); installCheck.onsuccess = function() { if(installCheck.result) { button.style.display = "none"; } else { button.addEventListener('click', install, false); }; };
Let's run through briefly what is going on:
- We get a reference to the install button and store it in the variable
button
. - We use
navigator.mozApps.checkInstalled
to check whether the app defined by the manifest athttps://people.mozilla.com/~cmills/location-finder/manifest.webapp
is already installed on the device. This test is stored in the variableinstallCheck
. - When the test is successfully carried out, its success event is fired, therefore
installCheck.onsuccess = function() { ... }
is run. - We then test for the existence of
installCheck.result
using anif
statement. If it does exist, meaning that the app is installed, we hide the button. An install button isn't needed if it is already installed. - If the app isn't installed, we add a click event listener to the button, so the
install()
function is run when the button is clicked. - When the button is clicked and the
install()
function is run, we store the manifest file location in a variable calledmanifest_url
, and then install the app usingnavigator.mozApps.install(manifest_url)
, storing a reference to that installation in theinstallLocFind
variable. You'll notice that this installation also fires success and error events, so you can run actions dependent on whether the install happened successfully or not.
You may want to verify the implementation state of the API when first coming to Installable web apps.
Note: Installable open web apps have a "single app per origin" security policy; basically, you can't host more than one installable app per origin. This makes testing a bit more tricky, but there are still ways around this, such as creating different sub-domains for apps, testing them using the Firefox OS Simulator, or testing the install functionality on Firefox Aurora/Nightly, which allows you to install installable web apps on the desktop. See FAQs about apps manifests for more information on origins.
WebRT APIs (Permissions-based APIs)
There are a number of WebAPIs that are available but require permissions for that specific feature to be enabled. Apps may register permission requests within the manifest.webapp
file like so:
// New key in the manifest: "permissions" // Request access to any number of APIs // Here we request permissions to the systemXHR API "permissions": { "systemXHR": {} }
The three levels of permission are as follows:
- Normal — APIs that don't need any kind of special access permissions.
- Privileged — APIs available to developers to use in their applications, as long as they set access permissions in the app manifest files, and distribute them through a trusted source.
- Certified — APIs that control critical functions on a device, such as the call dialer and messaging services. These are generally not available for third party developers to use.
For more information on app permission levels, read Types of packaged apps. You can find out more information about what APIs require permissions, and what permissions are required, at App permissions.
It's important to note that not all Web APIs have been implemented within the Firefox OS Simulator.
Tools & Testing
Testing is incredibly important when supporting mobile devices. There are many options for testing installable open web apps.
Firefox OS Simulator
Installing and using the Firefox OS Simulator is the easiest way to get up and running with your app. After you install the simulator, it is accessible from the Tools -> Web Developer -> Firefox OS Simulator menu. The simulator launches with a JavaScript console so you can debug your application from within the simulator.
App Manager
The new kid on the block with regards to testing tools is called the App Manager. This tool allows you to connect desktop Firefox to a compatible device via USB (or a Firefox OS simulator), push apps straight to the device, validate apps, and debug them as they run on the device.
Unit Testing
Unit tests are extremely valuable when testing on different devices and builds. jQuery's QUnit is a popular client-side testing utility, but you can use any set of testing tools you'd like.
Installing Firefox OS on a Device
Since Firefox OS is an open source platform, code and tools are available to build and install Firefox OS on your own device. Build and installation instructions, as well as notes on what devices it can be installed on, can be found on MDN.
Dedicated Firefox OS developer preview devices are also available: read our Developer preview phone page for more information.
App Submission and Distribution
Once your app is complete, you can host it yourself like a standard web site or app (read Self-publishing apps for more information), or it can be submitted to the Firefox Marketplace. Your app's manifest will be validated and you may choose which devices your app will support (e.g. Firefox OS, Desktop Firefox, Firefox Mobile, Firefox Tablet). Once validated, you can add additional details about your app (screenshots, descriptions, price, etc.) and officially submit the app for listing within the Marketplace. Once approved, your app is available to the world for purchase and installation.