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

 

This article provides a quick introduction to installable open web apps — installable on Firefox OS and other supporting platforms — including how they are created and how they differ from standard web apps/websites. This is written to make sense to both web developers and native mobile developers.

A message saying I love the web, along with devices of different screen sizes to represent the modern web's responsive nature.

Open web apps are essentially no different to standard websites or web apps. They are built using standard open web technologies — HTML, CSS, JavaScript, etc. — and can be accessed using a web browser. The main differences lie in their ability to be installed on devices and work offline, access to advanced APIs that allow interaction with device features such as camera, gyroscope and address book, and the existance of a solid developer ecosystem — including a Marketplace for distribution of free and paid apps. Generally, they provide users with an "app experience", while still being based on open, cross platform technologies.

Open web apps have a low barrier for entry, especially for existing web developers and mobile developers; they are also a lot more portable across platforms than native equivalents, and not locked into walled gardens.

Note: Open web apps are already installable on Firefox OS, and will soon be installable across multiple platforms via Mozilla's web run time technology (this is already available for Android.) In future, the technologies should be standardized and adopted across a wider range of platforms.

Firefox OS

Firefox OS (also referred to by its codename Boot to Gecko — or B2G) is Mozilla's open source mobile operating system. It's based on a Linux kernel, which boots into a Gecko-based runtime that lets users install and run open web appsGecko being the rendering engine that the Firefox browser uses to render and display web content.

Firefox OS comes with a suite of pre-installed applications called Gaia, which handles the fundamental functions of the phone such as settings, calls, SMS, taking and storing photos, etc.

支持跨Firefox OS的版本

Note that when developing apps for Firefox OS, you need to bear in mind what platform versions will be available on the devices your customers will have (see our available phones table for a list.) Remember that it is not as simple to update phone platform software as it is desktop software — users tend to be at the mercy of the network providers. You therefore need to develop apps to support these versions. This issue should go away soon, as more consumer Firefox OS devices appear, equipped with newer versions of Firefox OS out of the box.

The current baseline platform we recommended developing for is Firefox 1.1.

MDN's web platform reference pages include browser/platform support information, plus you can find support information for more App-specific technologies on our Apps API Reference.

As an example, multiline Flexbox doesn't work on Firefox OS versions below 1.3, so you may need to use a simpler layout method or provide a fallback for older versions.

技能 要求

As we've already mentioned Open Web Apps are based on web technologies — HTML, CSS, and JavaScript — so if you've written a web page you already know the basics. Even if you don't have the basics you'll be able to easily follow this guide, but you may want to check out our list of Beginner's tutorials to learn more about developing with open web technologies.

必备 工具

You can build open web apps with simple free tools, or make use of your existing web editing tools. We'd suggest getting hold of:

Once you get started you will want to run your web app on a Firefox OS phone; you can get adeveloper preview device or install your own build on an existing device, such as various supported Google Nexus models.

你的第一个应用程序

This section aims to get you up and running quickly with an installable web app, showing you how quick and easy it is to learn the basics. If you'd like to follow along with this guide, you can find our quickstart starter template repo on Github (download directly as a zip).

快速启动 应用程序 启动器 模板

Our app does something very simple — it uses the Battery Status API to fetch the battery charge level of the device and check to see whether the battery is charging or not, and alerts the user to the status of this via a vibration (via the Vibration API) and system notification (via the Notification API).

To begin with, the starter template directory has the following structure:

  • battery-quickstart-starter-template/
    • index.html
    • images/
      • battery.svg
      • icon-128.png
    • scripts/
      • battery.js
      • install.js
    • style/
      • style.css
    • .htaccess
    • README.md
  • index.html : The main document of our app that contains its content, and which everything else feeds into.
  • images : Contains an icon used in the app UI, plus the app icon itself.
  • scripts : Will contain the JavaScript code that defines the functionality of the app; currently there are two blank files — battery.js and install.js.
  • style : contains a stylesheet, style.css, to provide the app with basic styling.
  • .htaccess: A server config file that informs web servers of the mime type of the manifest file we are adding in the next section. This makes sure that servers don't throw an error if they don't recognise the manifest file type (which some might.)
  • README.md: Markdown-based readme file that Github uses to explain what this repo is all about.

添加一个manifest文件

Every open web app requires a manifest.webapp file to be placed in the app's root folder: This provides important information about the app, such as version, name, description, icon location, locale strings, domains the app can be installed from, and much more.

Add the following into a new plain text file in your app's root. Name the file manifest.webapp.

{
  "name": "Battery",
  "description": "Battery provides a good template for an in-app battery/charge indicator with different visualization choices, plus ideas of what could be changed once battery level gets low.",
  "launch_path": "/index.html",
  "icons": {
    "128": "/images/icon-128.png"
  },
  "developer": {
    "name": "Chris Mills",
    "url": "https://www.conquestofsteel.co.uk"
  },
  "permissions": {
    "desktop-notification": {
      "description": "Needed for creating system notifications."
    }
  }
}
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Note: For more information on exactly what is going on here, consult our App Manifestsreference.

Note: paths in manifest files should be relative to the origin of the server location. So for example, if my example's root is at https://www.mysite.com/myapp/, and my icon is athttps://www.mysite.com/myapp/myicon/icon.png, the icon path would be/myapp/myicon/icon.png, not /myicon/icon.png.

API的权限

There are a number of WebAPIs available that require permissions for that specific feature to be enabled. Installed apps have to register permission requests within the manifest.webappfile as seen in the "permissions" field above, which requests permission to use the system notifications controlled by the Notification API.

Different APIs require different levels of permission to access them. The three levels of permission are as follows:

  1. Normal — APIs that don't need any kind of special access permissions.
  2. 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.
  3. 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.

Note: For more information on what APIs require what permissions, read App permissions.

Web API 功能

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.

支持功能的特征检测

One technique employed commonly in web development is JavaScript feature detection — it involves running code to make sure a feature is supported by the browser before you actually try to use that feature. If it doesn't, you can provide some kind of fallback experience. The following snippet provides a quick example (this doesn't need to be added into your example code):

// Let's check if the browser supports notifications
if (!("Notification" in window)) {
  console.log("This browser does not support notifications.");
}
 
 
 
 

我们的快速入门例子功能的代码

Inside the scripts/battery.js file, add the following code blocks one after the other, reading the code comments carefully as you go. First, we'll set up all the variables we need:

// fork the navigator.battery object depending on what prefix the viewing browser uses
var battery = navigator.battery || navigator.mozBattery || navigator.webkitBattery;
// grab the elements we need, and put them in variables
var indicator1 = document.getElementById('indicator1');
var indicator2 = document.getElementById('indicator2');
var batteryCharge = document.getElementById('battery-charge');
var batteryTop = document.getElementById('battery-top');
var chargeIcon = document.getElementById('battery-charging');

// Flag to check if battery charged/not charged has already been notified once
// 0 for first time of notification,
// 1 means "charged" has already been notified,
// 2 means "not charged" has already been notified
// This is set to the opposite after each notification, so that you don't keep
// getting repeat notifications about the same charge state.
var chargingState = 0;
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Next, we'll add the main updateBatteryStatus() function, which is responsible for updating the displayed information about the battery's status whenever a battery-related event is fired:

function updateBatteryStatus() {
  // battery.level can be used to give us a percentage of bettery charge to report to
  // the app's user
  var percentage = Math.round(battery.level * 100);
  indicator1.innerHTML = "Battery charge at " + percentage + "%";
  batteryCharge.style.width = percentage + '%';
 
  if(percentage >= 99) {
    // report that the battery is fully charged, more or less ;-)
    batteryTop.style.backgroundColor = 'limegreen';
    batteryCharge.style.backgroundColor = 'limegreen';
    createNotification("Device battery fully charged.");
  }
 
  if(battery.charging) {
  // If the battery is charging  
    if(chargingState == 1 || chargingState == 0) {
    // and if our chargingState flag is equal to 0 or 1
      // alter the styling to show the battery charging
      batteryTop.style.backgroundColor = 'gold';
      batteryCharge.style.backgroundColor = 'gold';
      indicator2.innerHTML = "Battery is charging";
      chargeIcon.style.visibility = 'visible';
      // notify the user with a custom notification
      createNotification("Device battery now charging.");
      
      // flip the chargingState flag to 2
      chargingState = 2;
    }
  } else if(!battery.charging) {
  // If the battery is NOT charging
    if(chargingState == 2 || chargingState == 0) {
    // and if our chargingState flag is equal to 0 or 2
      // alter the styling to show the battery NOT charging
      batteryTop.style.backgroundColor = 'yellow';
      batteryCharge.style.backgroundColor = 'yellow';
      indicator2.innerHTML = "Battery not charging";
      chargeIcon.style.visibility = 'hidden';
      // notify the user with a custom notification
      createNotification("Device battery is not charging.");
      
      // flip the chargingState flag to 1
      chargingState = 1;
    }
  }
}
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Now it's time to add in the createNotification() function referenced above. When this is called, a system notification is fired containing the message passed in as its argument. This code seems a bit long-winded, but here we are both detecting support for Notifications, and handling bulletproof support for both Firefox and Chromium/Blink-based browsers.

function createNotification(message) {
  // Let's check if the browser supports notifications
  if (!("Notification" in window)) {
    console.log("This browser does not support notifications.");
  }
  // Let's check if the user is okay to get some notification
  else if (Notification.permission === "granted") {
    // If it's okay let's create a notification
    
    // show the notification  
    var notification = new Notification('Battery status', { body: message });
    // And vibrate the device if it supports vibration API
    window.navigator.vibrate(500);
  }
  // Otherwise, we need to ask the user for permission
  // Note, Chrome does not implement the permission static property
  // So we have to check for NOT 'denied' instead of 'default'
  else if (Notification.permission !== 'denied') {
    Notification.requestPermission(function (permission) {
      // Whatever the user answers, we make sure Chrome stores the information
      if(!('permission' in Notification)) {
        Notification.permission = permission;
      }
      // If the user is okay, let's create a notification
      if (permission === "granted") {
        
        // show the notification
        var notification = new Notification('Battery status', { body: message });
        // And vibrate the device if it supports vibration API
        window.navigator.vibrate(500);
      }
    });
  }
}
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Finally, we'll add event handlers to the battery object to let us respond to changes in the battery's charging state and charge level (by running the updateBatteryStatus() function), and then run updateBatteryStatus() once to get the show started:

// Event handler to check whether the battery has started charging or stopped charging
battery.addEventListener("chargingchange", updateBatteryStatus, false);
// Event handler to check whether the battery charge level has changed
battery.addEventListener("levelchange", updateBatteryStatus, false);

// run the central function once when the app is first loaded
updateBatteryStatus();
 
 
 
 
 
 
 

The comments should explain what the code does well enough, but the take home message is that it is easy to use hardware data and functionality via such APIs, with simple events and objects like chargingchangebattery, and Notification().

The JavaScript is watching for when the battery charge level changes, or when the battery stops or starts charging (the chargingchange and levelchange event listeners.) When one of these events happens, the updateBatteryStatus() function is run, which decides what notification to tell the user, updates the visual display to suit, and runscreateNotification().

This final function actually fires the system notification and makes the phone vibrate to give the user some extra system-wide feedback as to what the battery status is.

Note: Check the WebAPI page frequently to keep up to date with device API statuses.

安装 API 功能

In our sample 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">Install app on device</button>
 

This button's functionality will be implemented using the Install API. Add the following into your example's scripts/install.js file:

// get a reference to the install button
var button = document.getElementById('install');

// if browser has support for installable apps, run the install code; it not, hide the install button
if('mozApps' in navigator) {
    
    // define the manifest URL
    var manifest_url = location.href + 'manifest.webapp';
    
    function install(ev) {
      ev.preventDefault();
      // install the app
      var installLocFind = navigator.mozApps.install(manifest_url);
      installLocFind.onsuccess = function(data) {
        // App is installed, do something if you like
      };
      installLocFind.onerror = function() {
        // App wasn't installed, info is in
        // installapp.error.name
        alert(installLocFind.error.name);
      };
    };
    
    // if app is already installed, hide button. If not, add event listener to call install() on click
    var installCheck = navigator.mozApps.checkInstalled(manifest_url);
    installCheck.onsuccess = function() {
      
      if(installCheck.result) {
        button.style.display = "none";
      } else {
        button.addEventListener('click', install, false);
      };
    };
} else {
  button.style.display = "none";
}
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Again, the comments explain what's going on quite nicely, but in brief, we first check whether the mozApps object exists in the browser (if('mozApps' in navigator)) — i.e. if the browser supports installable apps or not. If not, we just hide the install button.

Next, navigator.mozApps.checkInstalled checks whether the app defined by the manifest at manifest_url is already installed on the device. If the test returns a success, its success event is fired and the installCheck.onsuccess = function() { ... } is run.

We then test for the existence of installCheck.result; if it does exist, meaning that the app is installed, we hide the install button. 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 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 errorevents, so you can run actions dependent on whether the install happened successfully or not.

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 subdomains for apps.

使应用程序可离线工作

By default, web apps (including hosted Firefox OS apps) don't work offline: resources are cached in the standard web way, but you can't guarantee the app will be available offline. There are various technologies and techniques that can be used to make apps work offline, and these are explained in more detail at our Offline apps developer recommendations page. We won't be discussing offline any further in this article, as we wanted to keep the scope clearly within the realm of distinct installable web app/Firefox OS app features.

测试你的应用程序

At this point, your app should be finished, and you can start testing it in browsers. If the app does not seem to be working, you can find the finished source code to check against, or see the example running live. For example, it looks like this on a desktop computer:

An image of the quickstart app in a desktop browser. it shows a title saying Battery indicator, and icons to indicate that the battery is not charging.

在Firefox 桌面版上进行测试

The quickest way to test your app's basic functionality is to simply load it in Firefox desktop (open the index.html file in the browser) — this supports most of the features we are talking about here. The notifications look like so on Mac OS X:

A system notification from Mac OS X saying that the device battery is not charging.

And in Firefox Aurora/Nightly and Firefox for Android, you can test the install functionality — these browsers include the Firefox runtime that allows installable web apps to be installed on the desktop.

Note: Bear in mind though that to test the install functionality you'll need to put the files onto a location on your own server that has no other installable web apps on the same origin (different subdomains is ok.) This is because of the "single app per origin" security policy we mentioned earlier. If you try to install the version we've got running on Github, for example, you'll get a MULTIPLE_APPS_PER_ORIGIN_FORBIDDEN error.

在Firefox OS 模拟器上进行测试

You can also test the app in a Firefox OS simulator via our App Manager tool. This will give you a more realistic idea of how it will look on a real device. In short, you need to:

  1. Install the Firefox OS simulator
  2. Open the App Manager (Tools > Web Developer > App Manager)
  3. Click Start Simulator then choose the simulator you installed earlier
  4. Click Add packaged app then navigate to your app's local directory
  5. Click the App's Update button to install it on the Firefox OS Simulator

在Firefox OS 移动设备上进行测试

The vibration API won't work on these options however. To fully test this you'll need to get hold of a real Firefox OS device. If you've got one, you can connect it to your computer and install apps contained on your local drive straight onto it via the App Manager. Here's a Firefox OS screenshot showing the app running, along with a system notification.

A Firefox OS screenshot showing the app, with a notification to say that the battery is charging.

To install the app on your Firefox OS device via the App Manager:

  1. Install the Firefox OS simulator and ADB helper
  2. Open the App Manager (Tools > Web Developer > App Manager)
  3. On your Firefox OS device, Select the ADB and Devtools option in the Remote Debuggingdeveloper setting
  4. Connect your phone to your desktop computer via USB
  5. Click the option that represents your device in the "Not connected" bar at the bottom of the App Manager. For example, a Geeksphone Keon usually appears as full_keon
  6. Click Add packaged app then navigate to your app's local directory
  7. Click the App's Update button to install it on the Firefox OS Device

应用程序提交和分发

Once your app is complete, you can host it yourself like a standard web site or app (read App publishing options for more information), self-publish a packaged app, submit it to the Firefox Marketplace. What you do here depends on your circumstances:

  1. When publishing a Firefox OS app, it is generally a good idea to make it available as a packaged app. Packaged apps come with the advantages of having access to privileged APIs (see App permissions), and being installed on the device so they are available offline. A packaged app would effectively get the AppCache functionality discussed above for free, and you could remove the install functionality discussed above as well (see Self-publishing packaged apps for more information on what you'd do instead.)
  2. If you want your app to be available as a general web app and not just a Firefox OS app, hosted is the way to go, as discussed in this article.

When submitting to the 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.

学习更多

That's it for now. Our quickstart is obviously a gross oversimplification of all the things involved in making a great app, but we've deliberately kept it this way to effectively highlight all the new things you need to know. For more information on different aspects of app design and development and Firefox OS, consult the below resources.

Firefox OS

Our Firefox OS zone focuses closely on the Firefox OS platform, giving you all need to know about building the platform, contributing to the Gaia project, phone specs, and Firefox OS-specific debugging and testing techniques.

设计应用程序

There's no "right way" to design a user interface, but there are plenty of ways to make your app less fun and easy to use. Our Apps design section will help you avoid making common UI mistakes, and provide knowledge of responsive design and other essential topics for designing an app that is a joy to use, no matter what platform it's running on.

构建应用程序

Our Apps build section provides clear developer recommandations and workflow advice to help experienced developers find solutions to common development problems rapidly, plus tutorials and API reference listings for those who want to go deeper.

发布应用程序

Want to get your app published and start forming a userbase? Our Marketplace zone contains all the information you need, including publishing options, submitting to the Firefox Marketplace, handing payments, and more.

常见问答(FAQ)

Frequently asked questions about app development basics.

我是否应该使用一个框架/库?

If you've got a certain framework or library that you tend to use often in your workflow, there is nothing to stop you creating an installable open web app with it.

这里是否有任何演示应用程序,我可以先试玩呢?

Yes, there are many available on the MDN App Center./zh-CN/docs/

文档标签和贡献者

 此页面的贡献者: xgqfrms, tangxiaobaobao, whyletgo, azzndmy, OlingCat, ReyCG_sub, markg
 最后编辑者: xgqfrms,