Las aplicaciones de la web abierta le dan a los desarrolladores lo que justamente han querido por años: un entorno multiplataforma dedicado a la construccion de aplicaciones con HTML, CSS y Javascript, con Firefox OS siendo la primera plataforma dedicada a las aplicaciones web. Esta guía tiene como objetivo iniciarte y orientarte rápidamente en una estructura básica e instrucciones de construcción, ¡de tal manera que tú puedas crear la siguiente generación de aplicaciones!
Si deseas continuar con esta guía, puedes descargar nuestro quick start app template. Encuentra más provechoso el contenido leyendo la guía Apps template.
Estructura de la Aplicación
Aplicaciones Empaquetadas vs. Aplicaciones Alojadas
Hay dos tipos de aplicaciones web abiertas: empaquetadas
y alojadas.
Las aplicaciones empaquetadas son esencialmente archivos zip
conteniendo todos los archivos necesarios: HTML, CSS, JavaScript, imágenes, manifest, etc. Las aplicaciones alojadas están corriendo desde un servidor en un dominio dado, como un sitio web estandard. Ambos tipos de aplicaciones requieren un manifest válido. Cuando llega el momento de listar tu aplicación en el Firefox Marketplace, ya sea que tu subas tu aplicación como un archivo zip o la URL del servidor donde está tu aplicación.
A los efectos de esta guía, crearás una aplicación alojada que vivirá en tu dirección localhost
. Una vez que tu aplicación esté lista para ser publicada en el Firefox Marketplace, podras tomar la decisión de agruparla como una aplicación empaquetada o lanzarla como una aplicación alojada.
Manifest de la Aplicación
Cada aplicación de Firefox requiere un archivo manifest.webapp en la raíz de la aplicación. El archivo manifest.webapp
proporciona información importante sobre la aplicación, como la versión, nombre, descripción, localización de íconos, strings locales, dominios donde la aplicación puede ser instalada, y mucho más. Sólo el nombre y la descripción son obligatorios. Una plantilla simple dentro de la aplicación es similar a lo que sigue:
{ "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 manifiesto básico es todo lo que necesitas para empezar. Para más detalles sobre los manifiestos, lee App Manifest.
App Layout & Design
El responsive design (diseño adaptativo) se ha convertido cada vez más importante a medida que más resoluciones de pantalla en diferentes dispositivos se convierten en la norma. Aunque el principal objetivo de tu aplicación sean las plataformas móviles como Firefox OS, otros dispositivos probablemente también tengan acceso a ella. Las CSS media queries permiten adaptar el diseño al dispositivo, como se muestra en este ejemplo de esqueleto en 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 */ }
Hay muchos frameworks JavaScript y CSS disponibles para ayudar en el diseño adaptativo y el desarrollo de aplicaciones móviles (Bootstrap, etc.). Elige el frameworks(s) que mejor se adapte a tu aplicación y estilo de desarrollo.
Web APIs
JavaScript APIs are being created and enhanced as quickly as devices are. 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.