-
Notifications
You must be signed in to change notification settings - Fork 1
/
iframe.html
73 lines (62 loc) · 2.27 KB
/
iframe.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
<!DOCTYPE html>
<html>
<head>
<title>Worker Iframe</title>
</head>
<body>
<script>
const allowedOrigin = window.location.origin;
let worker;
let lastObjectUrl = null;
let workerBlobUrls = [];
const originSource = "origin";
const iframeSource = "iframe";
const workerSource = "worker";
function postOriginMessage(message, source = iframeSource) {
window.parent.postMessage({message, source}, '*');
}
function postOriginResponse(requestEvent, message) {
window.parent.postMessage({id: requestEvent.data.id, response: true, message, source: iframeSource}, '*');
}
function postWorkerMessage(message, source = iframeSource) {
if (worker == null) return;
worker.postMessage({message, source});
}
function destroyWorker() {
if (worker == null) return;
worker.terminate();
worker = null;
}
window.addEventListener('message', async (event) => {
if (event.origin != allowedOrigin || event.data.source != 'origin') return;
const data = event.data.message;
if (data.loadWorker != null) {
if (worker != null) destroyWorker();
// Clear old data
if (lastObjectUrl != null) URL.revokeObjectURL(lastObjectUrl);
workerBlobUrls.forEach(url => URL.revokeObjectURL(lastObjectUrl));
workerBlobUrls = [];
// Create the worker from script
lastObjectUrl = URL.createObjectURL(
new Blob([data.loadWorker])
);
worker = new Worker(lastObjectUrl);
worker.onmessage = (e) => {
postOriginMessage(e.data, workerSource);
if (e.data.type == 'url') {
workerBlobUrls.push(e.data.content);
}
};
postOriginResponse(event, 'Worker created');
} else if (data.command === 'terminateWorker') {
destroyWorker();
postOriginResponse(event, 'Worker destroyed');
} else if (data.workerCommand) {
postWorkerMessage(data.workerCommand, event.data.source);
postOriginResponse(event, 'Worker message relayed from ' + event.data.source);
}
});
postOriginMessage('worker-loaded');
</script>
</body>
</html>