summaryrefslogtreecommitdiffstats
path: root/toolkit/components/webextensions/test/xpcshell/test_ext_schemas_api_injection.js
blob: 36d88d722273fcfc4b29335204d57aaabed0d6d1 (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
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
"use strict";

Components.utils.import("resource://gre/modules/ExtensionCommon.jsm");
Components.utils.import("resource://gre/modules/Schemas.jsm");

let {
  BaseContext,
  SchemaAPIManager,
} = ExtensionCommon;

let nestedNamespaceJson = [
  {
    "namespace": "backgroundAPI.testnamespace",
    "functions": [
      {
        "name": "create",
        "type": "function",
        "parameters": [
          {
            "name": "title",
            "type": "string",
          },
        ],
        "returns": {
          "type": "string",
        },
      },
    ],
  },
  {
    "namespace": "noBackgroundAPI.testnamespace",
    "functions": [
      {
        "name": "create",
        "type": "function",
        "parameters": [
          {
            "name": "title",
            "type": "string",
          },
        ],
      },
    ],
  },
];

let global = this;
class StubContext extends BaseContext {
  constructor() {
    let fakeExtension = {id: "test@web.extension"};
    super("addon_child", fakeExtension);
    this.sandbox = Cu.Sandbox(global);
    this.viewType = "background";
  }

  get cloneScope() {
    return this.sandbox;
  }
}

add_task(function* testSchemaAPIInjection() {
  let url = "data:," + JSON.stringify(nestedNamespaceJson);

  // Load the schema of the fake APIs.
  yield Schemas.load(url);

  let apiManager = new SchemaAPIManager("addon");

  // Register an API that will skip the background page.
  apiManager.registerSchemaAPI("noBackgroundAPI.testnamespace", "addon_child", context => {
    // This API should not be available in this context, return null so that
    // the schema wrapper is removed as well.
    return null;
  });

  // Register an API that will skip any but the background page.
  apiManager.registerSchemaAPI("backgroundAPI.testnamespace", "addon_child", context => {
    if (context.viewType === "background") {
      return {
        backgroundAPI: {
          testnamespace: {
            create(title) {
              return title;
            },
          },
        },
      };
    }

    // This API should not be available in this context, return null so that
    // the schema wrapper is removed as well.
    return null;
  });

  let context = new StubContext();
  let browserObj = {};
  apiManager.generateAPIs(context, browserObj);

  do_check_eq(browserObj.noBackgroundAPI, undefined);
  const res = browserObj.backgroundAPI.testnamespace.create("param-value");
  do_check_eq(res, "param-value");
});