mod.js 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  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. module.metadata = {
  6. "stability": "experimental"
  7. };
  8. const { Ci } = require("chrome");
  9. const method = require("../../method/core");
  10. const { add, remove, iterator } = require("../lang/weak-set");
  11. let getTargetWindow = method("getTargetWindow");
  12. getTargetWindow.define(function (target) {
  13. if (target instanceof Ci.nsIDOMWindow)
  14. return target;
  15. if (target instanceof Ci.nsIDOMDocument)
  16. return target.defaultView || null;
  17. return null;
  18. });
  19. exports.getTargetWindow = getTargetWindow;
  20. let attachTo = method("attachTo");
  21. exports.attachTo = attachTo;
  22. let detachFrom = method("detatchFrom");
  23. exports.detachFrom = detachFrom;
  24. function attach(modification, target) {
  25. let window = getTargetWindow(target);
  26. attachTo(modification, window);
  27. // modification are stored per content; `window` reference can still be the
  28. // same even if the content is changed, therefore `document` is used instead.
  29. add(modification, window.document);
  30. }
  31. exports.attach = attach;
  32. function detach(modification, target) {
  33. if (target) {
  34. let window = getTargetWindow(target);
  35. detachFrom(modification, window);
  36. remove(modification, window.document);
  37. }
  38. else {
  39. let documents = iterator(modification);
  40. for (let document of documents) {
  41. detachFrom(modification, document.defaultView);
  42. remove(modification, document);
  43. }
  44. }
  45. }
  46. exports.detach = detach;