sandbox.js 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  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 { Cc, Ci, CC, Cu } = require('chrome');
  9. const systemPrincipal = CC('@mozilla.org/systemprincipal;1', 'nsIPrincipal')();
  10. const scriptLoader = Cc['@mozilla.org/moz/jssubscript-loader;1'].
  11. getService(Ci.mozIJSSubScriptLoader);
  12. const self = require('sdk/self');
  13. /**
  14. * Make a new sandbox that inherits given `source`'s principals. Source can be
  15. * URI string, DOMWindow or `null` for system principals.
  16. */
  17. function sandbox(target, options) {
  18. options = options || {};
  19. options.metadata = options.metadata ? options.metadata : {};
  20. options.metadata.addonID = options.metadata.addonID ?
  21. options.metadata.addonID : self.id;
  22. return Cu.Sandbox(target || systemPrincipal, options);
  23. }
  24. exports.sandbox = sandbox;
  25. /**
  26. * Evaluates given `source` in a given `sandbox` and returns result.
  27. */
  28. function evaluate(sandbox, code, uri, line, version) {
  29. return Cu.evalInSandbox(code, sandbox, version || '1.8', uri || '', line || 1);
  30. }
  31. exports.evaluate = evaluate;
  32. /**
  33. * Evaluates code under the given `uri` in the given `sandbox`.
  34. *
  35. * @param {String} uri
  36. * The URL pointing to the script to load.
  37. * It must be a local chrome:, resource:, file: or data: URL.
  38. */
  39. function load(sandbox, uri) {
  40. if (uri.indexOf('data:') === 0) {
  41. let source = uri.substr(uri.indexOf(',') + 1);
  42. return evaluate(sandbox, decodeURIComponent(source), '1.8', uri, 0);
  43. } else {
  44. return scriptLoader.loadSubScript(uri, sandbox, 'UTF-8');
  45. }
  46. }
  47. exports.load = load;