Skip to content

Create Browser Prompts.js #293

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
184 changes: 184 additions & 0 deletions static/extensions/detectivesheepy/Browser Prompts.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,184 @@
/*
This extension was made with TurboBuilder!
https://turbobuilder-steel.vercel.app/
*/
(async function(Scratch) {
const variables = {};
const blocks = [];
const menus = {};


if (!Scratch.extensions.unsandboxed) {
alert("This extension needs to be unsandboxed to run!")
return
}

function doSound(ab, cd, runtime) {
const audioEngine = runtime.audioEngine;

const fetchAsArrayBufferWithTimeout = (url) =>
new Promise((resolve, reject) => {
const xhr = new XMLHttpRequest();
let timeout = setTimeout(() => {
xhr.abort();
reject(new Error("Timed out"));
}, 5000);
xhr.onload = () => {
clearTimeout(timeout);
if (xhr.status === 200) {
resolve(xhr.response);
} else {
reject(new Error(`HTTP error ${xhr.status} while fetching ${url}`));
}
};
xhr.onerror = () => {
clearTimeout(timeout);
reject(new Error(`Failed to request ${url}`));
};
xhr.responseType = "arraybuffer";
xhr.open("GET", url);
xhr.send();
});

const soundPlayerCache = new Map();

const decodeSoundPlayer = async (url) => {
const cached = soundPlayerCache.get(url);
if (cached) {
if (cached.sound) {
return cached.sound;
}
throw cached.error;
}

try {
const arrayBuffer = await fetchAsArrayBufferWithTimeout(url);
const soundPlayer = await audioEngine.decodeSoundPlayer({
data: {
buffer: arrayBuffer,
},
});
soundPlayerCache.set(url, {
sound: soundPlayer,
error: null,
});
return soundPlayer;
} catch (e) {
soundPlayerCache.set(url, {
sound: null,
error: e,
});
throw e;
}
};

const playWithAudioEngine = async (url, target) => {
const soundBank = target.sprite.soundBank;

let soundPlayer;
try {
const originalSoundPlayer = await decodeSoundPlayer(url);
soundPlayer = originalSoundPlayer.take();
} catch (e) {
console.warn(
"Could not fetch audio; falling back to primitive approach",
e
);
return false;
}

soundBank.addSoundPlayer(soundPlayer);
await soundBank.playSound(target, soundPlayer.id);

delete soundBank.soundPlayers[soundPlayer.id];
soundBank.playerTargets.delete(soundPlayer.id);
soundBank.soundEffects.delete(soundPlayer.id);

return true;
};

const playWithAudioElement = (url, target) =>
new Promise((resolve, reject) => {
const mediaElement = new Audio(url);

mediaElement.volume = target.volume / 100;

mediaElement.onended = () => {
resolve();
};
mediaElement
.play()
.then(() => {
// Wait for onended
})
.catch((err) => {
reject(err);
});
});

const playSound = async (url, target) => {
try {
if (!(await Scratch.canFetch(url))) {
throw new Error(`Permission to fetch ${url} denied`);
}

const success = await playWithAudioEngine(url, target);
if (!success) {
return await playWithAudioElement(url, target);
}
} catch (e) {
console.warn(`All attempts to play ${url} failed`, e);
}
};

playSound(ab, cd)
}
class Extension {
getInfo() {
return {
"id": "890",
"name": "Browser Prompts",
"color1": "#0091ff",
"color2": "#4900b8",
"color3": "#000000",
"blocks": blocks,
"menus": menus
}
}
}
blocks.push({
opcode: "1",
blockType: Scratch.BlockType.COMMAND,
text: "alert [2]",
arguments: {
"2": {
type: Scratch.ArgumentType.STRING,
defaultValue: (new Date(Date.now()).getFullYear()),
},
},
disableMonitor: true,
isEdgeActivated: false
});
Extension.prototype["1"] = async (args, util) => {
alert(args["2"])
};

blocks.push({
opcode: "3",
blockType: Scratch.BlockType.REPORTER,
text: "prompt [4]",
arguments: {
"4": {
type: Scratch.ArgumentType.STRING,
defaultValue: (new Date(Date.now()).getFullYear()),
},
},
disableMonitor: true,
isEdgeActivated: false
});
Extension.prototype["3"] = async (args, util) => {
return prompt(args["4"])
};

Scratch.extensions.register(new Extension());
})(Scratch);