Skip to content

Commit beab098

Browse files
committed
快照沙箱和代理沙箱
1 parent 5e718d0 commit beab098

File tree

3 files changed

+112
-0
lines changed

3 files changed

+112
-0
lines changed

demo.html

+39
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
<!DOCTYPE html>
2+
<html>
3+
<head>
4+
<title></title>
5+
</head>
6+
<body>
7+
<script type="text/javascript">
8+
class ProxySandbox{
9+
constructor(){
10+
const rawWindow = window;
11+
const fakeWindow = {};
12+
const proxy = new Proxy(fakeWindow,{
13+
set(target,p,value){
14+
target[p] = value;
15+
return true
16+
},
17+
get(target,p){
18+
return target[p] || rawWindow[p];
19+
}
20+
})
21+
this.proxy = proxy;
22+
}
23+
}
24+
25+
const sandbox1 = new ProxySandbox();
26+
const sandbox2 = new ProxySandbox();
27+
window.a = 1;
28+
((window) => {
29+
window.a = 'hello';
30+
console.log(window.a)
31+
})(sandbox1.proxy);
32+
33+
((window) => {
34+
window.a = 'world';
35+
console.log(window.a)
36+
})(sandbox2.proxy)
37+
</script>
38+
</body>
39+
</html>

proxy代理沙箱.js

+29
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
class ProxySandbox{
2+
constructor(){
3+
const rawWindow = window;
4+
const fakeWindow = {};
5+
const proxy = new Proxy(fakeWindow,{
6+
set(target,p,value){
7+
target[p] = value;
8+
return true
9+
},
10+
get(target,p){
11+
return target[p] || rawWindow[p];
12+
}
13+
})
14+
this.proxy = proxy;
15+
}
16+
}
17+
18+
const sandbox1 = new ProxySandbox();
19+
const sandbox2 = new ProxySandbox();
20+
window.a = 1;
21+
( ( window ) => {
22+
window.a = 'hello';
23+
console.log(window.a)
24+
} )(sandbox1.proxy)
25+
26+
( ( window ) => {
27+
window.a = 'hello';
28+
console.log(window.a)
29+
} )(sandbox2.proxy)

快照沙箱.js

+44
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
1+
//快照沙箱
2+
class SnapshotSandbox{
3+
constructor(){
4+
this.proxy = window;
5+
this.modifyPropMap = {};
6+
this.active();
7+
}
8+
// 激活
9+
active(){
10+
this.windowSnapshot = {};
11+
for(const prop in window){
12+
if(window.hasOwnProperty(prop)){
13+
this.windowSnapshot[prop] = window[prop];
14+
}
15+
}
16+
Object.keys(this.windowSnapshot).forEach(p => {
17+
window[p] = this.modifyPropMap[p];
18+
})
19+
}
20+
21+
// 失效
22+
inactive(){
23+
for(const prop in window){
24+
if(window.hasOwnProperty(prop)){
25+
if(window[prop] !== this.windowSnapshot[prop]){
26+
this.modifyPropMap[prop] = window[prop];
27+
window[prop] = this.windowSnapshot[prop];
28+
}
29+
}
30+
}
31+
}
32+
}
33+
34+
let sandbox = new SnapshotSandbox();
35+
36+
((window) => {
37+
window.a = 1;
38+
window.b = 2;
39+
console.log(window.a,window.b);
40+
sandbox.inactive();
41+
console.log(window.a,window.b);
42+
sandbox.active();
43+
console.log(window.a,window.b);
44+
})(sandbox.proxy)

0 commit comments

Comments
 (0)