-
Notifications
You must be signed in to change notification settings - Fork 1
/
sandbox.ts
76 lines (64 loc) · 2.02 KB
/
sandbox.ts
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
// @ts-nocheck
class Sandbox {
protected globalAddPropertyMap: Map<string | number | symbol, any> =
new Map();
protected globalBeforeUpdatePropertyMap: Map<string | number | symbol, any> =
new Map();
protected globalAfterUpdatePropertyMap: Map<string | number | symbol, any> =
new Map();
constructor(public name: string, protected proxy?: Object) {
const globalAddPropertyMap = this.globalAddPropertyMap;
const globalBeforeUpdatePropertyMap = this.globalBeforeUpdatePropertyMap;
const globalAfterUpdatePropertyMap = this.globalAfterUpdatePropertyMap;
const prevProxy = proxy || Object.create({});
this.proxy = new Proxy(prevProxy, {
get(_, name) {
return (window as any)[name];
},
set(_, name, value) {
if (prevProxy.hasOwnProperty && !prevProxy.hasOwnProperty(name)) {
globalAddPropertyMap.set(name, value);
}
if (!globalBeforeUpdatePropertyMap.has(name)) {
globalBeforeUpdatePropertyMap.set(name, (window as any)[name]);
}
globalAfterUpdatePropertyMap.set(name, value);
(window as any)[name] = value;
return true;
},
deleteProperty(target: any, p: string | symbol) {
delete target[p];
return true;
},
has() {
return true;
},
});
}
public active() {
for (let [key, val] of [...this.globalAfterUpdatePropertyMap]) {
(window as any)[key] = val;
}
}
public inactive() {
for (let [key, val] of [...this.globalBeforeUpdatePropertyMap]) {
(window as any)[key] = val;
}
for (let [key] of [...this.globalAddPropertyMap]) {
delete (window as any)[key];
}
}
public getProxy() {
return this.proxy;
}
public setProperty(key: string | number | symbol, val: any) {
(this.proxy as any)[key] = val;
}
}
var app = new Sandbox("App");
app.setProperty("main", "Tencent");
console.log(app.getProxy().main);
app.inactive();
console.log(app.getProxy().main);
app.active();
console.log(app.getProxy().main);