Search code examples
firefox-addonfirefox-addon-sdk

How can I log selected text with Firefox Addon Builder?


I have followed several tutorials with no success. I think this is the classic example but I can't make it work. I can save my project, install the addon and I can see the context menu item "Log Selection" when I select some text, but when I click on it nothing happens.

exports.main = function() {

    var contextMenu = require("context-menu");
    var request = require("request");
    var selection = require("selection");

    var menuItem = contextMenu.Item({
        label: "Log Selection",
        context: contextMenu.SelectionContext(),
        contentScript: 'self.on("click", function () {' +
                 '  var text = window.getSelection().toString();' +
                 '  self.postMessage(text);' +
                 '});',
        onMessage: function (selectionText) {
            alert(selectionText);
        }
    });
}

Even if my addon contains only one alert, the addon is installed but the alert is not shown.

exports.main = function() {
       alert("Hello world");
}

Extra info:


Solution

  • You cannot use alert directly in a lib/ module. There is simply no window that could display the alert and hence there is no alert function.

    Have a look instead at the Logging documentation.

    Should you really want to display something, you could e.g. use notifications, or alert using nsIPromptService (example on this page) or from within a content document (widget, etc).

    Here is an example showing off different methods.