worker.js 8.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282
  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": "unstable"
  7. };
  8. const { Class } = require('../core/heritage');
  9. const { EventTarget } = require('../event/target');
  10. const { on, off, emit, setListeners } = require('../event/core');
  11. const {
  12. attach, detach, destroy
  13. } = require('./utils');
  14. const { method } = require('../lang/functional');
  15. const { Ci, Cu, Cc } = require('chrome');
  16. const unload = require('../system/unload');
  17. const events = require('../system/events');
  18. const { getInnerId } = require("../window/utils");
  19. const { WorkerSandbox } = require('./sandbox');
  20. const { getTabForWindow } = require('../tabs/helpers');
  21. // A weak map of workers to hold private attributes that
  22. // should not be exposed
  23. const workers = new WeakMap();
  24. let modelFor = (worker) => workers.get(worker);
  25. const ERR_DESTROYED =
  26. "Couldn't find the worker to receive this message. " +
  27. "The script may not be initialized yet, or may already have been unloaded.";
  28. const ERR_FROZEN = "The page is currently hidden and can no longer be used " +
  29. "until it is visible again.";
  30. /**
  31. * Message-passing facility for communication between code running
  32. * in the content and add-on process.
  33. * @see https://addons.mozilla.org/en-US/developers/docs/sdk/latest/modules/sdk/content/worker.html
  34. */
  35. const Worker = Class({
  36. implements: [EventTarget],
  37. initialize: function WorkerConstructor (options) {
  38. // Save model in weak map to not expose properties
  39. let model = createModel();
  40. workers.set(this, model);
  41. options = options || {};
  42. if ('contentScriptFile' in options)
  43. this.contentScriptFile = options.contentScriptFile;
  44. if ('contentScriptOptions' in options)
  45. this.contentScriptOptions = options.contentScriptOptions;
  46. if ('contentScript' in options)
  47. this.contentScript = options.contentScript;
  48. if ('injectInDocument' in options)
  49. this.injectInDocument = !!options.injectInDocument;
  50. setListeners(this, options);
  51. unload.ensure(this, "destroy");
  52. // Ensure that worker.port is initialized for contentWorker to be able
  53. // to send events during worker initialization.
  54. this.port = createPort(this);
  55. model.documentUnload = documentUnload.bind(this);
  56. model.pageShow = pageShow.bind(this);
  57. model.pageHide = pageHide.bind(this);
  58. if ('window' in options)
  59. attach(this, options.window);
  60. },
  61. /**
  62. * Sends a message to the worker's global scope. Method takes single
  63. * argument, which represents data to be sent to the worker. The data may
  64. * be any primitive type value or `JSON`. Call of this method asynchronously
  65. * emits `message` event with data value in the global scope of this
  66. * symbiont.
  67. *
  68. * `message` event listeners can be set either by calling
  69. * `self.on` with a first argument string `"message"` or by
  70. * implementing `onMessage` function in the global scope of this worker.
  71. * @param {Number|String|JSON} data
  72. */
  73. postMessage: function (...data) {
  74. let model = modelFor(this);
  75. let args = ['message'].concat(data);
  76. if (!model.inited) {
  77. model.earlyEvents.push(args);
  78. return;
  79. }
  80. processMessage.apply(null, [this].concat(args));
  81. },
  82. get url () {
  83. let model = modelFor(this);
  84. // model.window will be null after detach
  85. return model.window ? model.window.document.location.href : null;
  86. },
  87. get contentURL () {
  88. let model = modelFor(this);
  89. return model.window ? model.window.document.URL : null;
  90. },
  91. get tab () {
  92. let model = modelFor(this);
  93. // model.window will be null after detach
  94. if (model.window)
  95. return getTabForWindow(model.window);
  96. return null;
  97. },
  98. // Implemented to provide some of the previous features of exposing sandbox
  99. // so that Worker can be extended
  100. getSandbox: function () {
  101. return modelFor(this).contentWorker;
  102. },
  103. toString: function () { return '[object Worker]'; },
  104. attach: method(attach),
  105. detach: method(detach),
  106. destroy: method(destroy)
  107. });
  108. exports.Worker = Worker;
  109. attach.define(Worker, function (worker, window) {
  110. let model = modelFor(worker);
  111. model.window = window;
  112. // Track document unload to destroy this worker.
  113. // We can't watch for unload event on page's window object as it
  114. // prevents bfcache from working:
  115. // https://developer.mozilla.org/En/Working_with_BFCache
  116. model.windowID = getInnerId(model.window);
  117. events.on("inner-window-destroyed", model.documentUnload);
  118. // Listen to pagehide event in order to freeze the content script
  119. // while the document is frozen in bfcache:
  120. model.window.addEventListener("pageshow", model.pageShow, true);
  121. model.window.addEventListener("pagehide", model.pageHide, true);
  122. // will set model.contentWorker pointing to the private API:
  123. model.contentWorker = WorkerSandbox(worker, model.window);
  124. // Mainly enable worker.port.emit to send event to the content worker
  125. model.inited = true;
  126. model.frozen = false;
  127. // Fire off `attach` event
  128. emit(worker, 'attach', window);
  129. // Process all events and messages that were fired before the
  130. // worker was initialized.
  131. model.earlyEvents.forEach(args => processMessage.apply(null, [worker].concat(args)));
  132. });
  133. /**
  134. * Remove all internal references to the attached document
  135. * Tells _port to unload itself and removes all the references from itself.
  136. */
  137. detach.define(Worker, function (worker) {
  138. let model = modelFor(worker);
  139. // maybe unloaded before content side is created
  140. if (model.contentWorker)
  141. model.contentWorker.destroy();
  142. model.contentWorker = null;
  143. if (model.window) {
  144. model.window.removeEventListener("pageshow", model.pageShow, true);
  145. model.window.removeEventListener("pagehide", model.pageHide, true);
  146. }
  147. model.window = null;
  148. // This method may be called multiple times,
  149. // avoid dispatching `detach` event more than once
  150. if (model.windowID) {
  151. model.windowID = null;
  152. events.off("inner-window-destroyed", model.documentUnload);
  153. model.earlyEvents.length = 0;
  154. emit(worker, 'detach');
  155. }
  156. model.inited = false;
  157. });
  158. /**
  159. * Tells content worker to unload itself and
  160. * removes all the references from itself.
  161. */
  162. destroy.define(Worker, function (worker) {
  163. detach(worker);
  164. modelFor(worker).inited = true;
  165. // Specifying no type or listener removes all listeners
  166. // from target
  167. off(worker);
  168. });
  169. /**
  170. * Events fired by workers
  171. */
  172. function documentUnload ({ subject, data }) {
  173. let model = modelFor(this);
  174. let innerWinID = subject.QueryInterface(Ci.nsISupportsPRUint64).data;
  175. if (innerWinID != model.windowID) return false;
  176. detach(this);
  177. return true;
  178. }
  179. function pageShow () {
  180. let model = modelFor(this);
  181. model.contentWorker.emitSync('pageshow');
  182. emit(this, 'pageshow');
  183. model.frozen = false;
  184. }
  185. function pageHide () {
  186. let model = modelFor(this);
  187. model.contentWorker.emitSync('pagehide');
  188. emit(this, 'pagehide');
  189. model.frozen = true;
  190. }
  191. /**
  192. * Fired from postMessage and emitEventToContent, or from the earlyMessage
  193. * queue when fired before the content is loaded. Sends arguments to
  194. * contentWorker if able
  195. */
  196. function processMessage (worker, ...args) {
  197. let model = modelFor(worker) || {};
  198. if (!model.contentWorker)
  199. throw new Error(ERR_DESTROYED);
  200. if (model.frozen)
  201. throw new Error(ERR_FROZEN);
  202. model.contentWorker.emit.apply(null, args);
  203. }
  204. function createModel () {
  205. return {
  206. // List of messages fired before worker is initialized
  207. earlyEvents: [],
  208. // Is worker connected to the content worker sandbox ?
  209. inited: false,
  210. // Is worker being frozen? i.e related document is frozen in bfcache.
  211. // Content script should not be reachable if frozen.
  212. frozen: true,
  213. /**
  214. * Reference to the content side of the worker.
  215. * @type {WorkerGlobalScope}
  216. */
  217. contentWorker: null,
  218. /**
  219. * Reference to the window that is accessible from
  220. * the content scripts.
  221. * @type {Object}
  222. */
  223. window: null
  224. };
  225. }
  226. function createPort (worker) {
  227. let port = EventTarget();
  228. port.emit = emitEventToContent.bind(null, worker);
  229. return port;
  230. }
  231. /**
  232. * Emit a custom event to the content script,
  233. * i.e. emit this event on `self.port`
  234. */
  235. function emitEventToContent (worker, ...eventArgs) {
  236. let model = modelFor(worker);
  237. let args = ['event'].concat(eventArgs);
  238. if (!model.inited) {
  239. model.earlyEvents.push(args);
  240. return;
  241. }
  242. processMessage.apply(null, [worker].concat(args));
  243. }