• Skip to main content
  • Select language
  • Skip to search
MDN Web Docs
  • Technologies
    • HTML
    • CSS
    • JavaScript
    • Graphics
    • HTTP
    • APIs / DOM
    • WebExtensions
    • MathML
  • References & Guides
    • Learn web development
    • Tutorials
    • References
    • Developer Guides
    • Accessibility
    • Game development
    • ...more docs
Add-ons
  1. MDN
  2. Mozilla
  3. Add-ons
  4. Add-on SDK
  5. Tutorials
  6. Creating Event Targets

Creating Event Targets

In This Article
  1. Using the Places API
  2. Modules as Event Targets
  3. Classes as Event Targets
    1. Implementing "onEvent" Options

Add-ons using the techniques described in this document are considered a legacy technology in Firefox. Don't use these techniques to develop new add-ons. Use WebExtensions instead. If you maintain an add-on which uses the techniques described here, consider migrating it to use WebExtensions.

From Firefox 53 onwards, no new legacy add-ons will be accepted on addons.mozilla.org (AMO).

From Firefox 57 onwards, WebExtensions will be the only supported extension type, and Firefox will not load other types.

Even before Firefox 57, changes coming up in the Firefox platform will break many legacy extensions. These changes include multiprocess Firefox (e10s), sandboxing, and multiple content processes. Legacy extensions that are affected by these changes should migrate to WebExtensions if they can. See the "Compatibility Milestones" document for more.

A wiki page containing resources, migration paths, office hours, and more, is available to help developers transition to the new technologies.

This tutorial describes the use of low-level APIs. These APIs are still in active development, and we expect to make incompatible changes to them in future releases.

The guide to event-driven programming with the SDK describes how to consume events: that is, how to listen to events generated by event targets. For example, you can listen to the tabs module's ready event or the Panel object's show event.

With the SDK, it's also simple to implement your own event targets. This is especially useful if you want to build your own modules, either to organize your add-on better or to enable other developers to reuse your code. If you use the SDK's event framework for your event targets, users of your module can listen for events using the SDK's standard event API.

In this tutorial we'll create part of a module to access the browser's Places API. It will emit events when the user adds and visits bookmarks, enabling users of the module to listen for these events using the SDK's standard event API.

Using the Places API

First, let's write some code using Places API that logs the URIs of bookmarks the user adds.

Create a new directory called "bookmarks", navigate to it, and run jpm init, accepting all the defaults. Then open "index.js" and add the following code:

var {Cc, Ci} = require("chrome");
var { XPCOMUtils } = require("resource://gre/modules/XPCOMUtils.jsm");
var bookmarkService = Cc["@mozilla.org/browser/nav-bookmarks-service;1"]
                          .getService(Ci.nsINavBookmarksService);
var bookmarkObserver = {
  onItemAdded: function(aItemId, aFolder, aIndex) {
    console.log("added ", bookmarkService.getBookmarkURI(aItemId).spec);
  },
  onItemVisited: function(aItemId, aVisitID, time) {
    console.log("visited ", bookmarkService.getBookmarkURI(aItemId).spec);
  },
  QueryInterface: XPCOMUtils.generateQI([Ci.nsINavBookmarkObserver])
};
exports.main = function() {
  bookmarkService.addObserver(bookmarkObserver, false);   
};
exports.onUnload = function() {
  bookmarkService.removeObserver(bookmarkObserver);
}

Try running this add-on, adding and visiting bookmarks, and observing the output in the console.

Modules as Event Targets

We can adapt this code into a separate module that exposes the SDK's standard event interface.

To do this we'll use the event/core module.

Create a new file in "lib" called "bookmarks.js", and add the following code:

var { emit, on, once, off } = require("sdk/event/core");
var {Cc, Ci} = require("chrome");
var { XPCOMUtils }= require("resource://gre/modules/XPCOMUtils.jsm");
var bookmarkService = Cc["@mozilla.org/browser/nav-bookmarks-service;1"]
                          .getService(Ci.nsINavBookmarksService);
var bookmarkObserver = {
  onItemAdded: function(aItemId, aFolder, aIndex) {
    emit(exports, "added", bookmarkService.getBookmarkURI(aItemId).spec);
  },
  onItemVisited: function(aItemId, aVisitID, time) {
    emit(exports, "visited", bookmarkService.getBookmarkURI(aItemId).spec);
  },
  QueryInterface: XPCOMUtils.generateQI([Ci.nsINavBookmarkObserver])
};
bookmarkService.addObserver(bookmarkObserver, false);
exports.on = on.bind(null, exports);
exports.once = once.bind(null, exports);
exports.removeListener = function removeListener(type, listener) {
  off(exports, type, listener);
};

This code implements a module which can emit added and visited events. It duplicates the previous code, but with a few changes:

  • import emit(), on(), once(), and off() from event/core
  • replace listener functions with calls to emit(), passing the appropriate event type
  • export its own event API. This consists of three functions:
    • on(): start listening for events or a given type
    • once(): listen for the next occurrence of a given event, and then stop
    • removeListener(): stop listening for events of a given type

The on() and once() exports delegate to the corresponding function from event/core, and use bind() to pass the exports object itself as the target argument to the underlying function. The removeListener() function is implemented by calling the underlying off() function.

We can use this module in the same way we use any other module that emits module-level events, such as tabs. For example, we can adapt "index.js" as follows:

var bookmarks = require("./bookmarks");
function logAdded(uri) {
  console.log("added: " + uri);
}
function logVisited(uri) {
  console.log("visited: " + uri);
}
exports.main = function() {
  bookmarks.on("added", logAdded);
  bookmarks.on("visited", logVisited);
};
exports.onUnload = function() {
  bookmarks.removeListener("added", logAdded);
  bookmarks.removeListener("visited", logVisited);
}

Classes as Event Targets

Sometimes we want to emit events at the level of individual objects, rather than at the level of the module.

To do this, we can inherit from the SDK's EventTarget class. EventTarget provides an implementation of the functions needed to add and remove event listeners: on(), once(), and removeListener().

In this example, we could define a class BookmarkManager that inherits from EventTarget and emits added and visited events.

Open "bookmarks.js" and replace its contents with this code:

var { emit } = require("sdk/event/core");
var { EventTarget } = require("sdk/event/target");
var { Class } = require("sdk/core/heritage");
var { merge } = require("sdk/util/object");
var {Cc, Ci} = require("chrome");
var { XPCOMUtils } = require("resource://gre/modules/XPCOMUtils.jsm");
var bookmarkService = Cc["@mozilla.org/browser/nav-bookmarks-service;1"]
                          .getService(Ci.nsINavBookmarksService);
function createObserver(target) {
   var bookmarkObserver = {
     onItemAdded: function(aItemId, aFolder, aIndex) {
       emit(target, "added", bookmarkService.getBookmarkURI(aItemId).spec);
     },
     onItemVisited: function(aItemId, aVisitID, time) {
       emit(target, "visited", bookmarkService.getBookmarkURI(aItemId).spec);
     },
     QueryInterface: XPCOMUtils.generateQI([Ci.nsINavBookmarkObserver])
   };
   bookmarkService.addObserver(bookmarkObserver, false);
}
var BookmarkManager = Class({
  extends: EventTarget,
  initialize: function initialize(options) {
    EventTarget.prototype.initialize.call(this, options);
    merge(this, options);
    createObserver(this);
  }
});
exports.BookmarkManager = BookmarkManager;

The code to interact with the Places API is the same here. However:

  • we're now importing from four modules:
    • event/core gives us emit(): note that we don't need on, once, or off, since we will use EventTarget for adding and removing listeners
    • event/target gives us EventTarget, which implements the interface for adding and removing listeners
    • core/heritage gives us Class(), which we can use to inherit from EventTarget
    • util/object gives us merge(), which just simplifies setting up the BookmarkManager's properties
  • we use Class to inherit from EventTarget. In its initialize() function, we:
    • call the base class initializer
    • use merge() to copy any supplied options into the newly created object
    • call createObserver(), passing in the newly created object as the event target
  • createObserver() is the same as in the previous example, except that in emit() we pass the newly created BookmarkManager as the event target

To use this event target we can create it and call the on(), once(), and removeListener() functions that it has inherited:

var bookmarks = require("./bookmarks");
var bookmarkManager = bookmarks.BookmarkManager({});
function logAdded(uri) {
  console.log("added: " + uri);
}
function logVisited(uri) {
  console.log("visited: " + uri);
}
exports.main = function() {
  bookmarkManager.on("added", logAdded);
  bookmarkManager.on("visited", logVisited);
};
exports.onUnload = function() {
  bookmarkManager.removeListener("added", logAdded);
  bookmarkManager.removeListener("visited", logVisited);
}

Implementing "onEvent" Options

Finally, most event targets accept options of the form "onEvent", where "Event" is the capitalized form of the event type. For example, you can listen to the Panel object's show event either by calling:

myPanel.on("show", listenerFunction);

or by passing the onShow option to Panel's constructor:

var myPanel = require("sdk/panel").Panel({
  onShow: listenerFunction,
  contentURL: "https://en.wikipedia.org/w/index.php"
});

If your class inherits from EventTarget, options like this are automatically handled for you. For example, given the implementation of BookmarkManager above, your "index.js" could be rewritten like this:

var bookmarks = require("./bookmarks");
function logAdded(uri) {
  console.log("added: " + uri);
}
function logVisited(uri) {
  console.log("visited: " + uri);
}
var bookmarkManager = bookmarks.BookmarkManager({
  onAdded: logAdded,
  onVisited: logVisited
});
exports.onUnload = function() {
  bookmarkManager.removeListener("added", logAdded);
  bookmarkManager.removeListener("visited", logVisited);
}

Document Tags and Contributors

 Contributors to this page: wbamberg, freaktechnik, Canuckistani
 Last updated by: wbamberg, Dec 1, 2016, 10:52:28 AM
See also
  1. WebExtensions
  2. Getting started
    1. What are WebExtensions?
    2. Your first WebExtension
    3. Your second WebExtension
    4. Anatomy of a WebExtension
    5. Example WebExtensions
  3. How to
    1. Intercept HTTP requests
    2. Modify a web page
    3. Add a button to the toolbar
    4. Implement a settings page
  4. Concepts
    1. Using the JavaScript APIs
    2. User interface components
    3. Content scripts
    4. Match patterns
    5. Internationalization
    6. Content Security Policy
    7. Native messaging
  5. Porting
    1. Porting a Google Chrome extension
    2. Porting a legacy Firefox add-on
    3. Embedded WebExtensions
    4. Comparison with the Add-on SDK
    5. Comparison with XUL/XPCOM extensions
    6. Chrome incompatibilities
  6. Firefox workflow
    1. Temporary Installation in Firefox
    2. Debugging
    3. Getting started with web-ext
    4. web-ext command reference
    5. WebExtensions and the Add-on ID
    6. Publishing your WebExtension
  7. JavaScript APIs
    1. Browser support for JavaScript APIs
    2. alarms
    3. bookmarks
    4. browserAction
    5. browsingData
    6. commands
    7. contextMenus
    8. contextualIdentities
    9. cookies
    10. downloads
    11. events
    12. extension
    13. extensionTypes
    14. history
    15. i18n
    16. identity
    17. idle
    18. management
    19. notifications
    20. omnibox
    21. pageAction
    22. runtime
    23. sessions
    24. sidebarAction
    25. storage
    26. tabs
    27. topSites
    28. webNavigation
    29. webRequest
    30. windows
  8. Manifest keys
    1. applications
    2. author
    3. background
    4. browser_action
    5. chrome_url_overrides
    6. commands
    7. content_scripts
    8. content_security_policy
    9. default_locale
    10. description
    11. developer
    12. homepage_url
    13. icons
    14. manifest_version
    15. name
    16. omnibox
    17. options_ui
    18. page_action
    19. permissions
    20. short_name
    21. sidebar_action
    22. version
    23. web_accessible_resources
  9. Add-on SDK
  10. Getting started
    1. Installation
    2. Getting started
    3. Troubleshooting
  11. High-Level APIs
    1. addon-page
    2. base64
    3. clipboard
    4. context-menu
    5. hotkeys
    6. indexed-db
    7. l10n
    8. notifications
    9. page-mod
    10. page-worker
    11. panel
    12. passwords
    13. private-browsing
    14. querystring
    15. request
    16. selection
    17. self
    18. simple-prefs
    19. simple-storage
    20. system
    21. tabs
    22. timers
    23. ui
    24. url
    25. webextension
    26. widget
    27. windows
  12. Low-Level APIs
    1. /loader
    2. chrome
    3. console/plain-text
    4. console/traceback
    5. content/content
    6. content/loader
    7. content/mod
    8. content/symbiont
    9. content/worker
    10. core/heritage
    11. core/namespace
    12. core/promise
    13. dev/panel
    14. event/core
    15. event/target
    16. frame/hidden-frame
    17. frame/utils
    18. fs/path
    19. io/byte-streams
    20. io/file
    21. io/text-streams
    22. lang/functional
    23. lang/type
    24. loader/cuddlefish
    25. loader/sandbox
    26. net/url
    27. net/xhr
    28. places/bookmarks
    29. places/favicon
    30. places/history
    31. platform/xpcom
    32. preferences/event-target
    33. preferences/service
    34. remote/child
    35. remote/parent
    36. stylesheet/style
    37. stylesheet/utils
    38. system/child_process
    39. system/environment
    40. system/events
    41. system/runtime
    42. system/unload
    43. system/xul-app
    44. tabs/utils
    45. test/assert
    46. test/harness
    47. test/httpd
    48. test/runner
    49. test/utils
    50. ui/button/action
    51. ui/button/toggle
    52. ui/frame
    53. ui/id
    54. ui/sidebar
    55. ui/toolbar
    56. util/array
    57. util/collection
    58. util/deprecate
    59. util/list
    60. util/match-pattern
    61. util/object
    62. util/uuid
    63. window/utils
  13. Firefox for Android
  14. Getting started
    1. Walkthrough
    2. Debugging
    3. Code snippets
  15. APIs
    1. Accounts.jsm
    2. BrowserApp
    3. HelperApps.jsm
    4. Home.jsm
    5. HomeProvider.jsm
    6. JavaAddonManager.jsm
    7. NativeWindow
    8. Notifications.jsm
    9. PageActions.jsm
    10. Prompt.jsm
    11. RuntimePermissions.jsm
    12. Snackbars.jsm
    13. Sound.jsm
    14. Tab
  16. Legacy
  17. Restartless extensions
    1. Overview
  18. Overlay extensions
    1. Overview
  19. Themes
  20. Lightweight themes
    1. Overview
  21. Complete themes
    1. Overview
  22. Publishing add-ons
  23. Guides
    1. Signing and distribution overview
    2. Submit an add-on
    3. Review policies
    4. Developer agreement
    5. Featured add-ons
    6. Contact addons.mozilla.org
  24. Community and support
  25. Channels
    1. Add-ons blog
    2. Add-on forums
    3. Stack Overflow
    4. Development newsgroup
    5. IRC Channel