Firefox OS - Spark – Developing addons for Firefox OS – Addons



Firefox OS - Spark – Developing addons for Firefox OS – Addons

1 3


Slides-Addons

Addons for Firefox OS

On Github CodingFree / Slides-Addons

Firefox OS - Spark

Developing addons for Firefox OS

Created by Mozilla

What is Spark?

Spark is a set of tools, customizations, and features built on top of the next generation of the Firefox OS platform

Spark is intended to empower users to customize their experience.

That is why addons comes into play.

Addons

Add-ons are a well-known concept in the world of web browsers.

This concept has been added to Firefox OS too!

But what are addons?

Add-ons are app packages composed of JavaScript, CSS, and other assets.

A single Firefox OS add-on can extend just one app, several, or all of them.

Lets build our first addon!

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.

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.

IMGUR Addon

{
  "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"
  }
}

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.

IMGUR Addon

This manifest.json will be inside the package.

But we want to publish it!

If we want any user to be able to install it we need another manifest.

It will be "update.webapp" and it will be hosted in our Web Hosting. That will let the Hackerplace to find it.

Pro tip: It has its own Content-Type, so check these for steps your hosting.

So it will look like...

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/*"].

Pro tip: match patterns.

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.

However, anything on the window object that is set by app code is available to add-ons. Similarly, the DOM is accessible as usual.

Considerations about the 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.

As a result, anything that is written to the window object from an add-on is unavailable to the app code.

However, anything on the window object that is set by app code is available to add-ons. Similarly, the DOM is accessible as usual.

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.

I recommend to set a private propery or variable to check whenever it has been loaded.

I usually do it in a constructor.

Example

(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();
}());

Web Workers

TODO

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.

Firefox OS - Spark Developing addons for Firefox OS Created by Mozilla