Mozilla's getting a new look. What do you think? https://mzl.la/brandsurvey

应用开发 FAQ

在本文章中
  1. 设备API和性能
    1. 怎样进行跨域请求?
    2. 如何显示通知?
    3. 是否可以获取网速或wifi和移动宽带之间的区别?
    4. Marketplace Review cited my app for not opening links in a new window!
    5. How can I run a background service?
    6. How can I get push notifications?
    7. How can I detect country/region and carrier from SIM card?
    8. How can I use a web activity to send an email?
    9. How can I share URLs through email?
    10. How can I open my listing in the marketplace?
    11. How can I detect whether an app is privileged or certified?
  2. Media
    1. How should I do media presentation?
    2. Do we support MP4/H264/MP3/AAC/etc?
    3. How can I play music in the background?
    4. How can I store downloaded files to the phone?
    5. Does Firefox OS Support HTTP Live Streaming (HLS)?
    6. How can I have DRM for music/video?
    7. Can I record video?
  3. App Development and publishing
    1. How can I protect business-critical assets/code?
    2. Can I have protected/encrypted storage on the phone for code/assets?
    3. Why is the phone too slow to run my game?
    4. How do I submit an updated version of my packaged App?
    5. Why doesn't my app update, even though I have updated the appcache manifest?
    6. How can I replace my hosted app with a packaged app?
    7. How do I push a packaged app to a device?
  4. Debugging
    1. How can I debug my app on the phone?
    2. Why is my App fast in the Simulator but painfully slow on the device?
    3. Why is my app being killed right on start-up?
    4. How do I debug memory use and OOM?
    5. Why do I get a different user agent?
    6. How can I tell where my phone is going for updates?
    7. Marketplace doesn’t launch or shows an error page
    8. I accidentally uninstalled the Marketplace, how do I get it back?
    9. What are useful commands during development?
    10. Why does my <meta name="viewport"> not work?
    11. Why am I getting an "address wasn't understood" error with AngularJS?
  5. Devices
    1. How do I update a Geeksphone Keon or Peak?

这篇翻译不完整。请帮忙从英语翻译这篇文章

这个FAQ是由我们业务发展和合作伙伴的工程团队每个星期所收到的常见问题和回答汇编而来。不论你是在寻找自己开发工作中遇到的问题的解决方法,或者其他感兴趣的人帮助别人寻找答案,你都可以在这儿发现许多有帮助的信息。如果你在文中找不到问题的答案,你可能需要更多的信息,看一下应用中心的其他内容,或者通过论坛联系我们

设备API和性能

怎样进行跨域请求?

这里有一些不同的可能解决方案:

  • 代理服务器:使用一个服务器代理所有的跨域请求。这需要你维护这样一个服务器。
  • JavaScript Object Notation with Padding (JSONP): 这种方式适用于许多环境,但是非常易用遭到跨站请求伪造(cross-site request forgery)的攻击,而且在特殊应用中不适用于加密服务提供程序(cryptographic service provider)
  • 跨域资源共享(Cross Origin Resource Sharing ,CORS): 这个要求修改响应头,但这个若不是你的服务器就没法控制了。启用CORS页面有一些入门级的介绍,而MDN上HTTP访问控制(CORS)页面包括更详细的指导和参考信息。对于可安装应用,你需要在你的应用清单中设置origin属性来让打包型应用知道这个已知来源。
  • SystemXHR-enabled XHR: 可安装应用 要求在manifest.webapp权限中的特权类型和systemXHR。用下面的方式来初始化你的XHR对象:
    new XMLHttpRequest({mozSystem: true});

    这是一个强大的权限会在审查期间得到额外的审查,小心使用!详情见XMLHttpRequest页面。

如何显示通知?

你可以在桌面火狐浏览器、Firefox for Android、 Firefox OS、Chrome and Safari使用系统通知。基本介绍见使用Web注意,而更详细的例子可以见通过Notification和Vibration API来通知用户

请留意在Firefox OS 1.2 (Gecko 26)中Notification API的改变。详情见使用 Web Notifications Gecko 注意事项 ,在一个来自Firefox OS IRC应用的例子中找到跨版本解决方案。

是否可以获取网速或wifi和移动宽带之间的区别?

是,可以利用网络信息API。详情见bug 713199

Your app will run in a chromeless runtime, without URL bar or navigation elements. When users navigate within your app to external websites, they can’t get back.

Within a running instance of a web app on Firefox OS, there is no browser chrome such as the navigation bar, refresh, home, or back buttons.  It’s important then to make sure that usage of your app does not depend on these features.  You can try disabling the browser chrome in Firefox by unchecking View > Toolbars > Navigation Toolbar and then navigating around your app.  If you link to a site outside of your own, with no means to return, then the user must close the app and restart it just to go back.  This is a poor user experience that we should try our best to avoid.

So how can we fix it?  One way is to open all links to external domains in a new tab using the target="_blank" attribute. Find a target blank example.  If you are not able to change all links, you can use an automated script that assigns the attribute on click. See also another example, which forces external links to open in a new window in Firefox OS.

How can I run a background service?

This can't be done yet, but it is a high priority for Firefox OS v1.2 (Q1 2014). Push notifications will also help.

How can I get push notifications?

Push notifications are available in Firefox OS 1.1 and above. See Simple Push on MDN.

How can I detect country/region and carrier from SIM card?

For privileged apps, the Mobile Connection API provides access to carrier and region codes; these need to be translated to the actual country codes. For a snippet that allows you to do this, look at Detect carrier and region from `mozMobileConnection`'s `MNC` and `MCC`.

How can I use a web activity to send an email?

Mozilla Hacks has an in-depth blog post about web activities, with technical details and several examples.

Specific example code:

new MozActivity({
    name: "new",
    data: {
           type: "mail",
           url: "mailto:?Subject=hello&body=world"
}
});

See also:

How can I share URLs through email?

This is not implemented correctly yet.

How can I open my listing in the marketplace?

Use web activities. See the Firefox Marketplace Web Activities guide for more specifics.

How can I detect whether an app is privileged or certified?

In your app, you can use Apps.getSelf() to get a DOMRequest object, and then onsuccess the request result will be an application object representing the app itself. You can then use the manifest property on the app object and the type property on the manifest to tell you if your app is privileged, certified, etc. An example follows:

var request = window.navigator.mozApps.getSelf();
request.onsuccess = function() {
    console.log("Your app's name is: " + request.result.manifest.name);
    console.log(request.result.manifest.name + " is a " + request.result.manifest.type + " app.");
};

Media

How should I do media presentation?

Currently, for security reasons, the h.264 decoder on Firefox OS devices is only available to privileged code. Because of that, you can't use the <video> element to present h.264 content at this time. You can, however, use a Web Activity. Here's a code snippet that can help:

var activity = new MozActivity({
  name: "view",
  data: {
    type: [
      "video/webm",
      "video/mp4",
      "video/3gpp",
      "video/youtube"
    ],
    url: "http://example.com/myvideo.mp4"
  }
});

This asks Firefox OS to present the MP4 video at the specified URL. You can include one or more video format types in the type list to permit.

Do we support MP4/H264/MP3/AAC/etc?

Firefox OS and Firefox on Android support additional codecs through hardware playback.

Support summary:

  • Video: OGG, WebM, MPEG 4 & H.264 (AAC or MP3)
  • Audio: MP3, AAC, M4A, OGG Vorbis, WAV

Read Supported media formats for more detail.

We recommend H.264 and MP3 for Firefox OS as it’s using hardware playback and therefore will use less CPU and battery.

Warning: Codecs that depend on hardware playback can not be tested in Firefox OS Simulator.

Known bugs: H.264 and WebM are disabled on 1.0.1.

See also:

How can I play music in the background?

This requires the audio-channel-content permission in manifest and setting the following property on audio objects/elements:

audio.mozAudioChannelType = 'content';

Permission is available to all apps.

This is subject to change in the future, as the behaviour is not well defined.

How can I store downloaded files to the phone?

The Device Storage API allows writing, reading and manipulation of files on the phones SD card, including access to the users music, videos and photos.

This API is privileged; it requires a packaged app and allows fine-grained permissions: see the device-storage:* permissions in our App permissions reference page.

Does Firefox OS Support HTTP Live Streaming (HLS)?

While HLS (HTTP Live Streaming) is a fantastic protocol, it's exclusive  to Apple and Apple has taken no steps to standardize it other than an  initial submission to the IETF.  There is the possibility of using another transmission protocol, but requiring adaptive bitrate streaming; to this end, we have implemented experimental support for Media Source  Extensions; you also have the options of streaming data over HTTP or WebSockets.

How can I have DRM for music/video?

We are evaluating the feasibility of EME.

Can I record video?

Yes, with MediaRecorder.

App Development and publishing

How can I protect business-critical assets/code?

Fact: Every bit of code on the client side can be "compromised". Developers need to understand and design accordingly.

You can make this harder via obfuscation with advanced compression (like Google closure compiler), and "bitcode"-style JavaScript generation via Emscripten and asm.js.

Some developers frown on JavaScript because native code requires obfuscation of source during compilation to run; JavaScript doesn't have to be obfuscated to run,  but it can be, easily.  Obfuscated JavaScript is analogous to compiled native code.  Someone could de-obfuscate JavaScript just as they could de-compile compiled native code, but there's still a loss of information (spacing, comments, variable names) in both cases.  And it is certainly possible for someone to analyze the obfuscated JavaScript code to fully understand what the code is doing, just as someone could analyze the bytecode of a compiled native binary; Rome wasn't built in a day, however.

For more detailed information and specific techniques, read Protecting your Firefox OS app code.

Can I have protected/encrypted storage on the phone for code/assets?

No, packaged apps are not encrypted. Developers can implement their own algorithms to store encrypted data but storing the secrets is another problem.

Why is the phone too slow to run my game?

Develop it with low-powered mobile phones in mind.

The best first step is to profile it maybe with the Firefox profiler or Webkit profiler, but this is better done through the phone.

General bottlenecks to avoid:

  • Reduce/remove some optional "juice" (effects, particles, blending/composition, post processing)
  • Don't scale images in your render loop with drawImage.
  • Don't scale the oversized canvas down with CSS to fit device.
  • Don't use heavy-weight libraries like Box2D, write physics to your own needs.
  • Be aware of garbage collection and the pauses it can introduce while creating/destroying game entities, re-use object from pools.
  • Use WebGL for rendering, Canvas still uses a lot of CPU!

For more information and specific code examples, read Optimizing your JavaScript game for Firefox OS.

How do I submit an updated version of my packaged App?

  1. Go to the Firefox Marketplace
  2. Sign in
  3. View submissions
  4. Click your app
  5. Click "Manage Status & Version" on left
  6. Click "Select a File..." under Upload New Version
  7. Submit updated .zip file

Why doesn't my app update, even though I have updated the appcache manifest?

Please check if you send Cache Headers for your appcache manifest. If you don't, Gecko will use heuristic caching and will serve it from its cache for a few hours. We recommend that you configure an immediate expiration for your appcache manifest. The following Apache config will do just that:

AddType text/cache-manifest .appcache
ExpiresByType text/cache-manifest "access"

This might be a good idea for your webapp manifest too:

AddType application/x-web-app-manifest+json .webapp
ExpiresByType application/x-web-app-manifest+json "access"

How can I replace my hosted app with a packaged app?

You have to upload it as a new app and disable the old app. There is no upgrade path for users provided by Marketplace at the moment.

To get the same URL/slug for the new app:

  1. Rename the old app's slug: Edit the listing page, click [Edit] on Basic Information and change the App URL, e.g. by appending -hosted
  2. Delist the old app on the Manage Status & Versions page
  3. Submit the new packaged app

How do I push a packaged app to a device?

The best way is to use the Firefox OS App Manager, which  requires Firefox OS 1.2 or above.

You can also using the Firefox OS Simulator if needed:

  1. Install the latest version of the Firefox OS Simulator Add-on in Firefox
  2. Open the simulator through the Firefox Menu: Tools > Web Developer > Firefox OS Simulator
  3. Add your app's manifest to the simulator dashboard (by pointing the  simulator to either your hosted manifest or a local copy of it)
  4. Connect the device
  5. Make sure that remote debugging is enabled on the device (Settings > Device Information > More Information > Developer > check Remote Debugging)
  6. With adb installed, run adb devices from the terminal and you should see your device listed. The simulator will recognize the device
  7. Click "Push to Device" for your app

Debugging

How can I debug my app on the phone?

The best way is to use the Firefox OS App Manager, which is compatible with Firefox OS 1.2 and above.

Alternatively, Install ADB and run adb logcat (Remote Debugging and Console needs to be enabled on the phone’s Developer Settings). Remote debugging from Firefox will be enabled in later versions.

logcat output can be filtered (only showing console logs, JS errors and filter out CSS warnings):

adb logcat GeckoConsole:* *:F | grep -vE "parsing value|Unknown property|declaration|invalid source| but found |pseudo-"

Why is my App fast in the Simulator but painfully slow on the device?

Profiling results are very different between Desktop and phone, due to different Firefox versions and hardware. We recommend profiling on the device!

Why is my app being killed right on start-up?

Your app got killed probably due to excessive memory use or memory spikes (Out-Of-Memory; OOM).

Causes:

  • localStorage access causing memory spikes
  • Loading and processing large images
  • Memory leaks

How do I debug memory use and OOM?

Look for sigkill being sent to your app.  The size is listed in pages (4 KB/page). This is done via

adb shell dmesg | tail -20

The following shows the memory usage of processes on the device, at a high level.

adb shell b2g-procrank

There is also a script available: get_about_memory, which gets about:memory information off the phone. It's the same info we get in the browser if you type about:memory into the location bar. This doesn't work on Windows.

Steps to investigate OOM crashes:

  • Check adb shell dmesg to ensure that the crash is actually due to OOM. If it is, you'll see something about the LMK sending SIGKIL to the app process.
  • Run get_about_memory every few seconds. Getting a memory report is not very expensive (if you don't have DMD enabled), so if you can get a memory report soon before the app crashes, we can get a lot of info that way.

For more information, read Debugging out of memory errors on Firefox OS.

Why do I get a different user agent?

Some websites are on a whitelist to send a different user agent. This is to force the website to serve the mobile website if it doesn’t recognize the B2G user agent.

Check if the website is on this whitelist.

Why does my app stop rendering on load without error?

This may be due to

  • GPU Out Of Memory or Long-running script got stopped without notice (see bug 921519 for more details)
  • View contains many scaled down images

How can I tell where my phone is going for updates?

Browse the phone storage using adb shell and look in:

  • /system/b2g/defaults/pref/user.js
  • /data/b2g/mozilla/[profile]/prefs.js

mozilla-central/b2g/app/b2g.js -> http://update.boot2gecko.org/[channel]/update.xml

Marketplace doesn’t launch or shows an error page

The time in your device probably isn’t set correctly. it is highly likely that it is still set to some date in 1980. The big year difference causes invalid HTTPS certificates.

Set the correct time, date and timezone in Settings > Time & Date

I accidentally uninstalled the Marketplace, how do I get it back?

To re-install the marketplace:

  1. In the browser application on device go to the Firefox Marketplace
  2. Click the gear icon in the top right to open settings
  3. Change the region dropdown to Worldwide, hit ok, then Save Changes
  4. After settings are saved, use the Marketplace search "marketplace" without the quotes
  5. If you successfully changed your region to worldwide then Marketplace should be the first result
  6. Click Free, then Install

What are useful commands during development?

In the commands below, the output is piped through colored-logcat, remove if not used.

Heavily filtered log (only JS logs and errors)

alias b2g-log='adb logcat GeckoConsole:* *:F | grep -vE "parsing value|Unknown property|declaration|invalid source| but found |pseudo-" | ~/bin/coloredlogcat.py'

Mostly log (no CSS warnings)

alias b2g-log-all='adb logcat | grep -vE "parsing value|Unknown property|declaration|invalid source| but found |pseudo-" | ~/bin/coloredlogcat.py'

Show running processes

alias b2g-ps='watch -n1 adb shell b2g-ps'

Restart B2G on device (faster than a power cycling)

alias b2g-restart='adb shell stop b2g && adb shell start b2g'

Edit device prefs (Sublime), store them and restart device

alias b2g-pref='adb pull /system/b2g/defaults/pref/user.js ~/Downloads/user.js && 
subl ~/Downloads/user.js --wait && 
adb shell mount -o rw,remount /system && 
adb push ~/Downloads/user.js /system/b2g/defaults/pref/user.js && 
adb shell mount -o ro,remount /system && 
adb reboot'

Why does my <meta name="viewport"> not work?

This is currently only supported in the browser and not in installable apps. For more information, read bug 830306 and bug 845690.

Why am I getting an "address wasn't understood" error with AngularJS?

If you have developed a packaged app with AngularJS, you may run into this error message:

The address wasn't understood 
Firefox doesn't know how to open this address, because the protocol (unsafe) isn't associated with any program. 

When you use Angular data binding to generate a URL, Angular will match the URL against its whitelist. If the URL does not match, Angular prefixes the url with "unsafe:" (see the Angular documentation). To make you app work with AngularJS, you can add "app:/"--the protocol FirefoxOS packaged apps use--to Angular's whitelist. In your app's configuration, this is how to whitelist "app:/":

var app = angular.module( 'myApp', [] ).config(['$compileProvider', function($compileProvider) {
        $compileProvider.urlSanitizationWhitelist(/^\s*(https?|ftp|mailto|app):/);
    }
]);

Or in AngularJS 1.1+

var app = angular.module( 'myApp', [] ).config(['$compileProvider', function($compileProvider) {
        $compileProvider.aHrefSanitizationWhitelist(/^\s*(https?|ftp|mailto|app):/);
    }
]);

Devices

How do I update a Geeksphone Keon or Peak?

See Updating and Tweaking your Firefox OS Developer Preview phone/Geeksphone

The easy way: Geeksphone provide updates on a public download server:

  1. Go to the Geeksphone download server.
  2. Download the latest stable or nightly build for your device
  3. Unzip the downloaded assets
  4. Connect device
  5. Enable remote debugging on device (Settings > Device Information > More Information > Developer > Remote Debugging)
  6. Run ./flash.sh from the unzipped downloaded assets

The hard way: Replace app.update.url with B2G Nightly updates:

  1. Grab and edit the user.js preferences from the phone (the following command uses Sublime, change if needed):
    adb pull /system/b2g/defaults/pref/user.js ~/Downloads/user.js &&
    subl ~/Downloads/user.js --wait &&
    adb shell mount -o rw,remount /system &&
    adb push ~/Downloads/user.js /system/b2g/defaults/pref/user.js &&
    adb shell mount -o ro,remount /system &&
    adb reboot
  2. Find pref("app.update.url", "http://gpfos.s3.amazonaws.com/keon/update.xml");
  3. Change the URL value to http://update.boot2gecko.org/nightly/update.xml
  4. Save and close your editor, the previous command will put the updated prefs back and relaunch b2g

You can force OTA updates using Check Now in the Firefox OS Settings. Changes in user.js should be persisted between updates, but I am not sure.

The hardest way: Flash only gecko and gaia.

文档标签和贡献者

 此页面的贡献者: baiyangcao
 最后编辑者: baiyangcao,