Skip to content

Instantly share code, notes, and snippets.

@AlttiRi
Last active June 4, 2022 18:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save AlttiRi/17b22dd2eca503d556e6bac3a6ddf743 to your computer and use it in GitHub Desktop.
Save AlttiRi/17b22dd2eca503d556e6bac3a6ddf743 to your computer and use it in GitHub Desktop.
ReadableStream demo extension
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>background.html</title>
<script src="background.js" type="module"></script>
</head>
<body></body>
</html>
const url = "https://giant.gfycat.com/GrimGrossKoodoo.mp4";
chrome.runtime.onConnect.addListener(async function(port) {
console.log(port);
if (port.name === "demo-fetch") {
let i = 0;
const response = await fetch(url, {cache: "force-cache"});
const reader = response.body.getReader();
while (true) {
const {done, /** @type {Uint8Array} */ value} = await reader.read();
const blob = new Blob([value]);
const url = URL.createObjectURL(blob)
new Promise(resolve => setTimeout(resolve, 1000)).then(() => URL.revokeObjectURL(url));
port.postMessage({
done,
value: url,
i: i++
});
if (done) {
break;
}
}
}
});
let resolve;
let promise;
function updatePromise() {
promise = new Promise(_resolve => {
resolve = _resolve;
});
}
updatePromise();
const port = chrome.runtime.connect({name: "demo-fetch"});
port.onMessage.addListener(async function({done, value, i}) {
console.log({done, value, i});
const ab = await fetch(value).then(r => r.arrayBuffer());
const u8a = new Uint8Array(ab);
console.log(i, u8a);
resolve({done, value: u8a, i});
updatePromise();
});
console.log("Create ReadableStream");
try {
rs = new ReadableStream({
async start(controller) {
while (true) {
const {done, value} = await promise;
if (done) {
break;
}
controller.enqueue(value);
}
controller.close();
}
});
} catch (e) {
console.error(e);
}
console.log("ReadableStream is created", rs);
new Response(rs)
.blob()
.then(blob => {
console.log(blob);
const a = document.createElement("a");
a.href = URL.createObjectURL(blob);
a.download = "GrimGrossKoodoo.mp4";
a.click();
new Promise(resolve => setTimeout(resolve, 1000)).then(() => URL.revokeObjectURL(a.href));
});
{
"manifest_version": 2,
"name": "readable-stream-demo",
"short_name": "rs-demo",
"description": "ReadableStream demo extension",
"version": "1.0",
"content_scripts": [
{
"matches": ["<all_urls>"],
"js": ["content.js"],
"run_at": "document_start"
}
],
"background": {
"page": "background.html",
"persistent": true
},
"permissions": ["<all_urls>", "activeTab", "tabs"]
}
{
"name": "readable-stream-extension-demo",
"version": "1.0.0",
"type": "module"
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment