Twiter: #moztechspeakers
Addons
Add-ons, or Web Extensions, are packages composed of JavaScript, CSS, and other assets.
A single Firefox OS add-on can extend just one app, several, or all of them.
WebExtensions will behave like other Firefox add-ons; they will be signed by Mozilla, and discoverable through addons.mozilla.org (AMO) or through the developer’s website. With this API
This concept has been added to Firefox OS too!

Twiter: #moztechspeakers
Our first addon
This addon will take any screnshot taken with out device and will upload it to IMGUR.
It will be attached to the system app: system.gaiamobile.org
That means that it will inherit the permissions of the target app: since system.gaiamobile.org is certified, the addon will inherit the same permissions.
Twiter: #moztechspeakers
IMGUR Addon
It must have a manifest file.
It will be a Chrome manifest, quite different from the manifests used for Firefox OS Webapps.
Manifest File Format: Field summary.
Twiter: #moztechspeakers
IMGUR Addon
The "matches" field is what is used to attach the addon to any app.
It uses origin + entry point (index.html)
The js and css fields are the assets attached to the target.
{
"manifest_version": 2,
"version": "2.0",
"name": "IMGUR Screenshots",
"description": "Send a screenshot to IMGUR.",
"author": "Adrian Crespo, Giovanny Gongora",
"role": "addon",
"type": "certified",
"content_scripts": [{
"matches": ["app://system.gaiamobile.org/index.html"],
"css": [],
"js": ["imgur.js"]
}],
"icons": {
"512": "/style/icons/512.png",
"256": "/style/icons/256.png",
"128": "/style/icons/128.png",
"90": "/style/icons/90.png",
"64": "/style/icons/64.png",
"48": "/style/icons/48.png",
"32": "/style/icons/32.png",
"16": "/style/icons/16.png"
}
}
Twiter: #moztechspeakers
IMGUR Addon
This manifest.json will be inside the package.

Twiter: #moztechspeakers
Supported Fields
- name
- version
- description
- content_scripts
- permissions
- web_accessible_resources
- background
- browser_action
- default_locale
Twiter: #moztechspeakers
Injecting the code
In the content_script field, we specified our script:
"js": ["imgur.js"]
We are attaching that script to a Web App that whose url matches a regular expresion.
We are matching a local app,
app://system.gaiamobile.org/index.html
but it could be even a Website, like
["http://www.mozilla.com/*"].
For any website or any app it would be:
["<all_urls>"]
Pro tip: match patterns.
Twiter: #moztechspeakers
The window object
Add-ons only share a proxied version of the content window.
As a result, anything that is written to the window object from an add-on is unavailable to the app code.

Twiter: #moztechspeakers
The window object
If the caller has lower privileges than the target object, then the caller gets an opaque wrapper.
An opaque wrapper denies all access to the target object.
However, the privileged target can use exportFunction()
and cloneInto()
.

Twiter: #moztechspeakers
Loading window object
When an app is already running and an add-on that targets it is enabled. in such a case, a window.onload handler won't work.
Your injected script needs to wait for the dom to be loaded before doing anything.
You can use "load" or "DOMContentLoaded".
if (document.documentElement) {
initialize();
} else {
window.addEventListener('load', initialize);
}
function initialize() {
..
}
Twiter: #moztechspeakers
Preventing multiple injections
To prevent an add-on from being injected into a single app instance multiple times, you should check whether your add-on is already present.
Think about window.setInterval(), window.setTimeout() or synchronous XMLHttpRequests.
I recommend to set a private propery or variable to check whenever it has been loaded.
I usually do it in a constructor.
The official documentation uses this example:
if (document.querySelector('.fxos-banner'))
Twiter: #moztechspeakers
Example
- It does not check if the window object was been fully loaded.
- It prevents multiple injections.
- It uses mozChromeEvent
- volume-up-button-released
- handle-crash
- Etcetera
(function () {
function uploader() {
console.log("Object created!");
this._started = false;
uploader.prototype.start();
}
uploader.prototype = {
/**
* Start to handle screenshot events.
* @memberof Screenshot.prototype
*/
start: function () {
console.log("IMGUR Running");
if (this._started) {
throw 'Instance should not be start()\'ed twice.';
}
this._started = true;
window.addEventListener('mozChromeEvent', this);
},
/**
* Stop handling screenshot events.
* @memberof Screenshot.prototype
*/
stop: function () {
if (!this._started) {
throw 'Instance was never start()\'ed but stop() is called.';
}
this._started = false;
window.removeEventListener('mozChromeEvent', this.handleEvent);
},
/**
* Handle screenshot events.
* @param {DOMEvent} evt DOM Event to handle.
* @memberof Screenshot.prototype
*/
handleEvent: function (evt) {
switch (evt.type) {
case 'mozChromeEvent':
if (evt.detail.type === 'take-screenshot-success') {
console.log("There is an screenshot available.");
if(navigator.onLine){
this.handleTakeScreenshotSuccess(evt.detail.file);
}
} else if (evt.detail.type === 'take-screenshot-error') {
this.notify('screenshotFailed', evt.detail.error);
}
break;
default:
console.debug('Unhandled event: ' + evt.type);
break;
}
},
/**
* Handle the take-screenshot-success mozChromeEvent.
* @param {Blob} file Blob object received from the event.
* @memberof Screenshot.prototype
*/
handleTakeScreenshotSuccess: function (file) {
try {
var self = this;
var fd = new FormData();
fd.append("image", file);
var xhr = new XMLHttpRequest();
xhr.open('POST', 'https://api.imgur.com/3/image');
xhr.setRequestHeader('Authorization', 'Client-ID 440d44a2a741339');
xhr.onload = function() {
var data = JSON.parse(xhr.responseText).data;
var imgurURL = data.link;
console.log(imgurURL);
self.notify('Screenshot uploaded: ', imgurURL, null, true);
//const gClipboardHelper = Components.classes["@mozilla.org/widget/clipboardhelper;1"].getService(Components.interfaces.nsIClipboardHelper);
//gClipboardHelper.copyString(imgurURL);
};
xhr.send(fd);
} catch (e) {
console.log('exception in screenshot handler', e);
this.notify('screenshotFailed', e.toString());
}
},
/**
* Display a screenshot success or failure notification.
* Localize the first argument, and localize the third if the second is null
* @param {String} titleid l10n ID of the string to show.
* @param {String} body Label to show as body, or null.
* @param {String} bodyid l10n ID of the label to show as body.
* @param {String} onClick Optional handler if the notification is clicked
* @memberof Screenshot.prototype
*/
//TODO: l10n
notify: function (titleid, body, bodyid, onClick) {
console.log("A notification would be send: " + titleid);
var notification = new window.Notification(titleid, {
body: body,
icon: '/style/icons/Gallery.png'
});
notification.onclick = function () {
notification.close();
if (onClick) {
new MozActivity({
name: "view",
data: {
type: "url",
url: body
}
});
}
};
}
};
console.log("Lets start!");
var uploader = new uploader();
}());
Twiter: #moztechspeakers
Yet another addon
Firefox Adblocker
This is the manifest file:
{
"manifest_version": 2,
"version": "1.0",
"name": "FXOS Adblocker",
"description": "Block those nasty ads.",
"author": "Adrian Crespo",
"role": "addon",
"type": "certified",
"content_scripts": [
{
"matches": ["<all_urls>"],
"js": [
"scripts/blocker.js"
]
}
],
"permissions": ["<all_urls>"],
"icons": {
"512": "/style/icons/512.png",
"256": "/style/icons/256.png",
"128": "/style/icons/128.png",
"90": "/style/icons/90.png",
"64": "/style/icons/64.png",
"48": "/style/icons/48.png",
"32": "/style/icons/32.png",
"16": "/style/icons/16.png"
}
}
(work in progress, it is the consequence of having too much coffeine)
Twiter: #moztechspeakers
Yet another addon
Firefox Adblocker
- It checks if the window object was been fully loaded (NEEDED).
- It prevents multiple injections.
- It does not remove ads yet, it only remove the pictures from any app (as a proof of concept).
- It doesn't use "launch_at".
(function () {
function uploader() {
console.log("Object created!");
this._started = false;
uploader.prototype.start();
}
uploader.prototype = {
/**
* Start to handle screenshot events.
* @memberof Screenshot.prototype
*/
start: function () {
console.log("IMGUR Running");
if (this._started) {
throw 'Instance should not be start()\'ed twice.';
}
this._started = true;
window.addEventListener('mozChromeEvent', this);
},
/**
* Stop handling screenshot events.
* @memberof Screenshot.prototype
*/
stop: function () {
if (!this._started) {
throw 'Instance was never start()\'ed but stop() is called.';
}
this._started = false;
window.removeEventListener('mozChromeEvent', this.handleEvent);
},
/**
* Handle screenshot events.
* @param {DOMEvent} evt DOM Event to handle.
* @memberof Screenshot.prototype
*/
handleEvent: function (evt) {
switch (evt.type) {
case 'mozChromeEvent':
if (evt.detail.type === 'take-screenshot-success') {
console.log("There is an screenshot available.");
if(navigator.onLine){
this.handleTakeScreenshotSuccess(evt.detail.file);
}
} else if (evt.detail.type === 'take-screenshot-error') {
this.notify('screenshotFailed', evt.detail.error);
}
break;
default:
console.debug('Unhandled event: ' + evt.type);
break;
}
},
/**
* Handle the take-screenshot-success mozChromeEvent.
* @param {Blob} file Blob object received from the event.
* @memberof Screenshot.prototype
*/
handleTakeScreenshotSuccess: function (file) {
try {
var self = this;
var fd = new FormData();
fd.append("image", file);
var xhr = new XMLHttpRequest();
xhr.open('POST', 'https://api.imgur.com/3/image');
xhr.setRequestHeader('Authorization', 'Client-ID 440d44a2a741339');
xhr.onload = function() {
var data = JSON.parse(xhr.responseText).data;
var imgurURL = data.link;
console.log(imgurURL);
self.notify('Screenshot uploaded: ', imgurURL, null, true);
//const gClipboardHelper = Components.classes["@mozilla.org/widget/clipboardhelper;1"].getService(Components.interfaces.nsIClipboardHelper);
//gClipboardHelper.copyString(imgurURL);
};
xhr.send(fd);
} catch (e) {
console.log('exception in screenshot handler', e);
this.notify('screenshotFailed', e.toString());
}
},
/**
* Display a screenshot success or failure notification.
* Localize the first argument, and localize the third if the second is null
* @param {String} titleid l10n ID of the string to show.
* @param {String} body Label to show as body, or null.
* @param {String} bodyid l10n ID of the label to show as body.
* @param {String} onClick Optional handler if the notification is clicked
* @memberof Screenshot.prototype
*/
//TODO: l10n
notify: function (titleid, body, bodyid, onClick) {
console.log("A notification would be send: " + titleid);
var notification = new window.Notification(titleid, {
body: body,
icon: '/style/icons/Gallery.png'
});
notification.onclick = function () {
notification.close();
if (onClick) {
new MozActivity({
name: "view",
data: {
type: "url",
url: body
}
});
}
};
}
};
console.log("Lets start!");
var uploader = new uploader();
}());
Twiter: #moztechspeakers
But we want to publish it!
If you use the Hackerplace, you could install addons by their url.
Sadly, it does not work for the Marketplace (yet).
It will be "update.webapp" and it will be hosted in our Web Hosting. That will let the Hackerplace to find it.
You must specify their Content-Type, so check these steps for your hosting. For example, if you use Apache it would be:
AddType application/x-web-app-manifest+json .webapp
Twiter: #moztechspeakers
So it will look like...

Twiter: #moztechspeakers
And the content will be...
It is also a JSON document, mostly used to define the icons and where is the package.
{
"name" : "NFC Sleep",
"description": "Turn off your WiFi and volume using a NFC Tag.",
"developer": { "name": "Adrian Crespo" },
"package_path": "package.zip",
"icons": {
"512": "/style/icons/512.png",
"256": "/style/icons/256.png",
"128": "/style/icons/128.png",
"90": "/style/icons/90.png",
"64": "/style/icons/64.png",
"48": "/style/icons/48.png",
"32": "/style/icons/32.png",
"16": "/style/icons/16.png"
}
}
And what about the Marketplace?
There is an open Beta to upload the addons to the Marketplace. Just follow this link.
Twiter: #moztechspeakers
And they are available!

Twiter: #moztechspeakers
Best practices
- Never use synchronous XMLHttpRequests.
- Performing sequential, asynchronous operations can often be greatly simplified using Promises.
- Avoid writing slow CSS.
- Avoid DOM mutation event listeners.
- Using window.setInterval() or window.setTimeout() can be problematic, too.
- Clean up event listeners.
- Don't store references to window objects and DOM nodes for too long.
Twiter: #moztechspeakers
Current status
So, are they currently supported?
Not yet but...
They are a feature for Firefox 42 and Firefox OS 2.5
Twiter: #moztechspeakers
Thanks for attending!
Twitter: @CodingFree
Email: madrid.crespo@gmail.com

Twiter: #moztechspeakers
deck
By firefoxos
deck
- 982