1 /* Copyright 2024 Mozilla Foundation
3 * Licensed under the Apache License, Version 2.0 (the "License");
4 * you may not use this file except in compliance with the License.
5 * You may obtain a copy of the License at
7 * http://www.apache.org/licenses/LICENSE-2.0
9 * Unless required by applicable law or agreed to in writing, software
10 * distributed under the License is distributed on an "AS IS" BASIS,
11 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 * See the License for the specific language governing permissions and
13 * limitations under the License.
16 export class SandboxSupportBase {
19 this.timeoutIds = new Map();
24 for (const id of this.timeoutIds.values()) {
25 this.win.clearTimeout(id);
27 this.timeoutIds = null;
29 exportValueToSandbox(val) {
30 throw new Error("Not implemented");
32 importValueFromSandbox(val) {
33 throw new Error("Not implemented");
35 createErrorForSandbox(errorMessage) {
36 throw new Error("Not implemented");
38 callSandboxFunction(name, args) {
43 args = this.exportValueToSandbox(args);
44 this.commFun(name, args);
46 this.win.console.error(e);
49 createSandboxExternals() {
51 setTimeout: (callbackId, nMilliseconds) => {
52 if (typeof callbackId !== "number" || typeof nMilliseconds !== "number") {
55 if (callbackId === 0) {
56 this.win.clearTimeout(this.timeoutIds.get(callbackId));
58 const id = this.win.setTimeout(() => {
59 this.timeoutIds.delete(callbackId);
60 this.callSandboxFunction("timeoutCb", {
65 this.timeoutIds.set(callbackId, id);
67 clearTimeout: callbackId => {
68 this.win.clearTimeout(this.timeoutIds.get(callbackId));
69 this.timeoutIds.delete(callbackId);
71 setInterval: (callbackId, nMilliseconds) => {
72 if (typeof callbackId !== "number" || typeof nMilliseconds !== "number") {
75 const id = this.win.setInterval(() => {
76 this.callSandboxFunction("timeoutCb", {
81 this.timeoutIds.set(callbackId, id);
83 clearInterval: callbackId => {
84 this.win.clearInterval(this.timeoutIds.get(callbackId));
85 this.timeoutIds.delete(callbackId);
88 if (typeof cMsg !== "string") {
94 if (typeof cMsg !== "string") {
97 return this.win.confirm(cMsg);
99 prompt: (cQuestion, cDefault) => {
100 if (typeof cQuestion !== "string" || typeof cDefault !== "string") {
103 return this.win.prompt(cQuestion, cDefault);
106 const url = new this.win.URL(cUrl);
107 const props = ["hash", "host", "hostname", "href", "origin", "password", "pathname", "port", "protocol", "search", "searchParams", "username"];
108 return Object.fromEntries(props.map(name => [name, url[name].toString()]));
114 const event = new this.win.CustomEvent("updatefromsandbox", {
115 detail: this.importValueFromSandbox(data)
117 this.win.dispatchEvent(event);
120 Object.setPrototypeOf(externals, null);
121 return (name, args) => {
123 const result = externals[name](...args);
124 return this.exportValueToSandbox(result);
126 throw this.createErrorForSandbox(error?.toString() ?? "");