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