F'fox Extension Example js


In the DOM and Events Task, there is a reference to Firefox Extension development.

In fact there is a related Study Group in formation http://new.p2pu.org/en/groups/mozilla-jetpack/.

I am just starting to have a look at this myself and thought it would be of interest to post the javascript code used in the introductory material for an add-on that will add a menu item to Firefox's context menu that causes replacement of selected text with its English translation.

 

<span>// Import the APIs we need.
var contextMenu = require("context-menu");
var request = require("request");
var selection = require("selection");
 
exports.main = function(options, callbacks) {
  console.log(options.loadReason);
 
  // Create a new context menu item.
  var menuItem = contextMenu.Item({
 
    label: "Translate Selection",
 
    // Show this item when a selection exists.
 
    context: contextMenu.SelectionContext(),
 
    // When this item is clicked, post a message to the item with the
    // selected text and current URL.
    contentScript: 'self.on("click", function () {' +
                   '  var text = window.getSelection().toString();' +
                   '  self.postMessage(text);' +
                   '});',
 
    // When we receive the message, call the Google Translate API with the
    // selected text and replace it with the translation.
    onMessage: function (text) {
      if (text.length == 0) {
        throw ("Text to translate must not be empty");
      }
      console.log("input: " + text)
      var req = request.Request({
        url: "<a href="http://ajax.googleapis.com/ajax/services/language/translate">http://ajax.googleapis.com/ajax/services/language/translate</a>",
        content: {
          v: "1.0",
          q: text,
          langpair: "|en"
        },
        onComplete: function (response) {
          translated = response.json.responseData.translatedText;
          console.log("output: " + translated)
          selection.text = translated;
        }
      });
      req.get();
    }
  });
};
 
exports.onUnload = function (reason) {
  console.log(reason);
};
</span>

 

As I work through through the material I might try and explain what is going on here (can't say when).

Anyone else looking into it can chime in, of course.

Task Discussion