summaryrefslogtreecommitdiffstats
path: root/mobile/android/chrome/content/EmbedRT.js
blob: 8e35a3b634dbdab3a5aa7c77321e7b26ccecd899 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this file,
 * You can obtain one at http://mozilla.org/MPL/2.0/. */
"use strict";

XPCOMUtils.defineLazyModuleGetter(this, "ConsoleAPI",
                                  "resource://gre/modules/Console.jsm");

/*
 * Collection of methods and features specific to using a GeckoView instance.
 * The code is isolated from browser.js for code size and performance reasons.
 */
var EmbedRT = {
  _scopes: {},

  observe: function(subject, topic, data) {
    switch(topic) {
      case "GeckoView:ImportScript":
        this.importScript(data);
        break;
    }
  },

  /*
   * Loads a script file into a sandbox and calls an optional load function
   */
  importScript: function(scriptURL) {
    if (scriptURL in this._scopes) {
      return;
    }

    let principal = Cc["@mozilla.org/systemprincipal;1"].createInstance(Ci.nsIPrincipal);

    let sandbox = new Cu.Sandbox(principal,
      {
        sandboxName: scriptURL,
        wantGlobalProperties: ["indexedDB"]
      }
    );

    sandbox["console"] = new ConsoleAPI({ consoleID: "script/" + scriptURL });
    sandbox["GeckoView"] = {
      sendRequest: function(data) {
        if (!data) {
          throw new Error("Invalid parameter: 'data' can't be null.");
        }

        let message = { type: "GeckoView:Message", data: data };
        Messaging.sendRequest(message);
      },
      sendRequestForResult: function(data) {
        if (!data) {
          throw new Error("Invalid parameter: 'data' can't be null.");
        }

        let message = { type: "GeckoView:Message", data: data };
        return Messaging.sendRequestForResult(message);
      }
    };

    // As we don't want our caller to control the JS version used for the
    // script file, we run loadSubScript within the context of the
    // sandbox with the latest JS version set explicitly.
    sandbox.__SCRIPT_URI_SPEC__ = scriptURL;
    Cu.evalInSandbox("Components.classes['@mozilla.org/moz/jssubscript-loader;1'].createInstance(Components.interfaces.mozIJSSubScriptLoader).loadSubScript(__SCRIPT_URI_SPEC__);", sandbox, "ECMAv5");

    this._scopes[scriptURL] = sandbox;

    if ("load" in sandbox) {
      let params = {
        window: window,
        resourceURI: scriptURL,
      };

      try {
        sandbox["load"](params);
      } catch(e) {
        dump("Exception calling 'load' method in script: " + scriptURL + "\n" + e);
      }
    }
  }
};