blob: a79869b2f96249969d44e5f18341fa1cbd094f4d (
plain)
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
|
<!DOCTYPE html>
<meta charset="utf-8">
<title>SharedWorker Blob Fetcher</title>
<script>
window.addEventListener("message", function (evt) {
let { url } = evt.data;
const workerScriptContent = `
async function doFetch(url) {
const response = await fetch(url);
const body = await response.text();
return {
status: response.status,
body,
};
}
async function fetchAndPost(url, port) {
try {
const message = await doFetch(url);
port.postMessage(message);
} catch(e) {
port.postMessage({ error: e.name });
}
}
const url = "${url}";
self.addEventListener("connect", async (evt) => {
await fetchAndPost(url, evt.ports[0]);
});
`;
const blob =
new Blob([workerScriptContent], {type: 'application/javascript'});
const workerScriptUrl = URL.createObjectURL(blob);
const worker = new SharedWorker(workerScriptUrl);
URL.revokeObjectURL(workerScriptUrl);
worker.onerror = (evt) => {
parent.postMessage({ error: evt.message || "unknown error" }, "*");
};
worker.port.addEventListener("message", (evt) => {
parent.postMessage(evt.data, "*");
});
worker.port.start();
});
</script>
|