addon-sdk/source/lib/sdk/content/utils.js

branch
TOR_BUG_3246
changeset 7
129ffea94266
equal deleted inserted replaced
-1:000000000000 0:89c90613a2b5
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': 'unstable'
8 };
9
10 let { merge } = require('../util/object');
11 let assetsURI = require('../self').data.url();
12 let isArray = Array.isArray;
13 let method = require('../../method/core');
14
15 function isAddonContent({ contentURL }) {
16 return typeof(contentURL) === 'string' && contentURL.indexOf(assetsURI) === 0;
17 }
18 exports.isAddonContent = isAddonContent;
19
20 function hasContentScript({ contentScript, contentScriptFile }) {
21 return (isArray(contentScript) ? contentScript.length > 0 :
22 !!contentScript) ||
23 (isArray(contentScriptFile) ? contentScriptFile.length > 0 :
24 !!contentScriptFile);
25 }
26 exports.hasContentScript = hasContentScript;
27
28 function requiresAddonGlobal(model) {
29 return model.injectInDocument || (isAddonContent(model) && !hasContentScript(model));
30 }
31 exports.requiresAddonGlobal = requiresAddonGlobal;
32
33 function getAttachEventType(model) {
34 if (!model) return null;
35 let when = model.contentScriptWhen;
36 return requiresAddonGlobal(model) ? 'document-element-inserted' :
37 when === 'start' ? 'document-element-inserted' :
38 when === 'ready' ? 'DOMContentLoaded' :
39 when === 'end' ? 'load' :
40 null;
41 }
42 exports.getAttachEventType = getAttachEventType;
43
44 let attach = method('worker-attach');
45 exports.attach = attach;
46
47 let detach = method('worker-detach');
48 exports.detach = detach;
49
50 let destroy = method('worker-destroy');
51 exports.destroy = destroy;
52
53 function WorkerHost (workerFor) {
54 // Define worker properties that just proxy to underlying worker
55 return ['postMessage', 'port', 'url', 'tab'].reduce(function(proto, name) {
56 // Use descriptor properties instead so we can call
57 // the worker function in the context of the worker so we
58 // don't have to create new functions with `fn.bind(worker)`
59 let descriptorProp = {
60 value: function (...args) {
61 let worker = workerFor(this);
62 return worker[name].apply(worker, args);
63 }
64 };
65
66 let accessorProp = {
67 get: function () { return workerFor(this)[name]; },
68 set: function (value) { workerFor(this)[name] = value; }
69 };
70
71 Object.defineProperty(proto, name, merge({
72 enumerable: true,
73 configurable: false,
74 }, isDescriptor(name) ? descriptorProp : accessorProp));
75 return proto;
76 }, {});
77
78 function isDescriptor (prop) {
79 return ~['postMessage'].indexOf(prop);
80 }
81 }
82 exports.WorkerHost = WorkerHost;

mercurial