content-observer.js 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. /* This Source Code Form is subject to the terms of the Mozilla Public
  2. * License, v. 2.0. If a copy of the MPL was not distributed with this
  3. * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
  4. "use strict";
  5. const {Cc, Ci, Cu, Cr} = require("chrome");
  6. const Services = require("Services");
  7. const events = require("sdk/event/core");
  8. /**
  9. * Handles adding an observer for the creation of content document globals,
  10. * event sent immediately after a web content document window has been set up,
  11. * but before any script code has been executed.
  12. */
  13. function ContentObserver(tabActor) {
  14. this._contentWindow = tabActor.window;
  15. this._onContentGlobalCreated = this._onContentGlobalCreated.bind(this);
  16. this._onInnerWindowDestroyed = this._onInnerWindowDestroyed.bind(this);
  17. this.startListening();
  18. }
  19. module.exports.ContentObserver = ContentObserver;
  20. ContentObserver.prototype = {
  21. /**
  22. * Starts listening for the required observer messages.
  23. */
  24. startListening: function () {
  25. Services.obs.addObserver(
  26. this._onContentGlobalCreated, "content-document-global-created", false);
  27. Services.obs.addObserver(
  28. this._onInnerWindowDestroyed, "inner-window-destroyed", false);
  29. },
  30. /**
  31. * Stops listening for the required observer messages.
  32. */
  33. stopListening: function () {
  34. Services.obs.removeObserver(
  35. this._onContentGlobalCreated, "content-document-global-created", false);
  36. Services.obs.removeObserver(
  37. this._onInnerWindowDestroyed, "inner-window-destroyed", false);
  38. },
  39. /**
  40. * Fired immediately after a web content document window has been set up.
  41. */
  42. _onContentGlobalCreated: function (subject, topic, data) {
  43. if (subject == this._contentWindow) {
  44. events.emit(this, "global-created", subject);
  45. }
  46. },
  47. /**
  48. * Fired when an inner window is removed from the backward/forward cache.
  49. */
  50. _onInnerWindowDestroyed: function (subject, topic, data) {
  51. let id = subject.QueryInterface(Ci.nsISupportsPRUint64).data;
  52. events.emit(this, "global-destroyed", id);
  53. }
  54. };
  55. // Utility functions.
  56. ContentObserver.GetInnerWindowID = function (window) {
  57. return window
  58. .QueryInterface(Ci.nsIInterfaceRequestor)
  59. .getInterface(Ci.nsIDOMWindowUtils)
  60. .currentInnerWindowID;
  61. };