forked from omegaup/karel.js
-
Notifications
You must be signed in to change notification settings - Fork 0
/
sandbox.html
90 lines (90 loc) · 3.46 KB
/
sandbox.html
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
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<script type="text/javascript">
function parentPostMessage(id, data, error) {
var message = JSON.stringify({ id:id, data: data, error: error });
return parent.postMessage(message, "*")
};
(function(){
if (!window.Worker) {
parentPostMessage(void 0, void 0, "WebWorkers unsupported");
return;
}
var pending = {};
var SandboxedWorker = function(id, options) {
this.id = id;
this.options = {
timeout: 0
};
if (!options) {
options = {};
}
for (var prop in options) {
if (!options.hasOwnProperty(prop)) continue;
this.options[prop] = options[prop];
}
this.worker = null;
this.timer = null;
return this
};
SandboxedWorker.prototype = {
constructor: SandboxedWorker,
report: function(data, error) {
parentPostMessage(this.id, data, error);
},
run: function() {
var self = this;
if (self.options.timeout) {
self.timer = setTimeout(function() {
self.terminate();
self.report(void 0, "timeout");
}, self.options.timeout);
}
self.worker = new window.Worker('js/worker.js');
self.worker.addEventListener('message', function(message) {
var data = JSON.parse(message.data);
self.report(data.data, data.error);
});
self.worker.postMessage(JSON.stringify(self.options.input));
},
terminate: function() {
if (!this.worker) {
return;
}
if (this.timer) {
clearTimeout(this.timer);
}
this.timer = null;
this.worker.onmessage = null;
this.worker.terminate();
this.worker = null;
delete pending[this.id];
}
};
return window.addEventListener("message", function(message) {
var data = JSON.parse(message.data);
if(data.command === "run") {
if(data.id in pending) {
parentPostMessage(data.id, void 0, "running");
return;
}
var sw = new SandboxedWorker(data.id, data.options);
pending[data.id] = sw;
sw.run();
} else if(data.command === "terminate") {
if (!(data.id in pending)){
parentPostMessage(data.id, void 0, "terminated");
return;
}
pending[data.id].terminate();
}
});
}).call(this);
</script>
<title></title>
</head>
<body>
</body>
</html>