Source code

Revision control

Copy as Markdown

Other Tools

<!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>