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.

La tua prima app

Le applicazioni web aperte offrono agli sviluppatori esattamente quello che hanno voluto per anni: un ambiente multi-piattaforma dedicata alle applicazioni installabili create con solo HTLM, CSS e JavaScript — Firefox OS è la prima piattaforma aperta dedicata alle apllicazioni web. Questa guida si propone di farvi ottenere rapidamente le basi e le istruzioni di complicazione in modo da poter creare la prossima grande app!

Se vuoi seguire questa guida, è possibile scaricare il nostro modello di applicazione di avvio rapido. Trova più info leggendo la nostra guida sul modello dell'applicazioni.

Struttura di un'applicazione

Packaged vs. Hosted Apps

Ci sono due tipi di applicazioni web aperte: packaged e hosted. Le applicazioni Packaged sono essenzialmente formate da un file zip contenente tutto il necessario: HTML, CSS, JavaScript, immagini, manifest, etc. Le applicazioni Hosted (ospitate) sono eseguite e gestite da un server su un determinato dominio, proprio come un normale sito web. Entrambi i tipi di app richiedono un manifest valido. Quando arriva il momento di inserire la vostra app nel Marketplace di Firefox si carica sia l'app sotto forma di file zip che a indiciare l'url del dominio dove si trovano i vari file dell'applicazione sul server.

   Realizzato in collaborazione con Treehouse: DACCI UN'OCCHIATA!

Ai fini di questa guida, svilupperete la vostra applicazione Hosted in localhost. Un volta che l'applicazione è pronta di può decidere di caricarla nel Marketplace di Firefox come "Hosted App".

Manifest di una App

Ogni applicazione Firefox richiede un file manifest.webapp alla radice dell'app. Il file manifest.webapp fornisce importanti informazioni sull'app come: la versione, nome, descrizione, posizione delle icone e immagini, strighe locali, domini di dove l'app si andrà a installare, e molto altro (Solo il nome e la descrizione sono richieste). Il semploce manifest incluso in un applicazione si presenta:

{
  "version": "0.1",
  "name": "Open Web App",
  "description": "La vostra nuova App Web",
  "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": "Il tuo nome",
    "url": "https://sitodellapp.com"
  },
  "locales": {
    "es": {
      "description": "Su nueva aplicación impresionante Open Web",
      "developer": {
        "url": "https://yourawesomeapp.com"
      }
    },
    "it": {
      "description": "La vostra nuova fantastica Open Web App",
      "developer": {
        "url": "https://yourawesomeapp.com"
      }
    }
  },
  "default_locale": "it"
}

Realizzato in collaborazione con Treehouse: DACCI UN'OCCHIATA!

 

Un Manifest di base dovrà essere sempre la prima cosa da creare per la vostra app. Per maggiori info leggere l'App Manifest.

App Layout & Design

Il design responsive è diventato sempre più importante, se prendiamo in considerazione il fatto che le risoluzioni dello schermo dei vari device sono ormai diventate degli standard da seguire.
Anche se l'obiettivo principale della vostra applicazione, è quella di distribuirla sulle piattaforme mobili come Firefox OS, potette comunque rendere compatibile l'applicazione con le altre piattaforme. Per fare si che la vostra applicazioni adatti in automatico il layout in base al dispositivo, come mostrato in questo esempio, dovete utilizzare il CSS media queries:

/* 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 */
}

There are many JavaScript and CSS frameworks available to aid in responsive design and mobile app development (Bootstrap, etc.); choose the framework(s) that best fit your app and development style.

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. Of course JavaScript feature detection is still the best practice:

// If this device supports the vibrate API...
if('vibrate' in navigator) {
    // ... vibrate for a second
    navigator.vibrate(1000);
}

In the following example snippet we modify the display style of a <div> based on changes in the device's battery state:

// 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:

  1. We get a reference to the install button and store it in the variable button.
  2. We use navigator.mozApps.checkInstalled to check whether the app defined by the manifest at https://people.mozilla.com/~cmills/location-finder/manifest.webapp is already installed on the device. This test is stored in the variable installCheck.
  3. When the test is successfully carried out, its success event is fired, therefore installCheck.onsuccess = function() { ... } is run.
  4. We then test for the existance of installCheck.result using an if 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.
  5. 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.
  6. When the button is clicked and the install() function is run, we store the manifest file location in a variable called manifest_url, and then install the app using navigator.mozApps.install(manifest_url), storing a reference to that installation in the installLocFind variable. You'll notice that this installation also fires success and error events, so you can run actions dependant 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 allow installable web apps to install 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 installed the simulator is accessible via the Tools -> Web Developer -> Firefox OS Simulator menu. The simulator launches with a JavaScript console so that you may 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 (i.e. Firefox OS, Desktop Firefox, Firefox Mobile, Firefox Tablet). Once validated you may 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.

More Marketplace & Listing Information

  1. Submitting an App to the Firefox OS Marketplace
  2. Marketplace Review Criteria
  3. App Submission Video Walkthrough

Tag del documento e collaboratori

 Hanno collaborato alla realizzazione di questa pagina: maybe, florin88, mscarcy
 Ultima modifica di: maybe,