Skip to content
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

Add local storage extension #55

Merged
merged 13 commits into from
May 15, 2023
69 changes: 69 additions & 0 deletions local-storage.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,69 @@
(function (Scratch) {
'use strict';
if (!Scratch.extensions.unsandboxed) {
throw new Error('Local Storage must be run unsandboxed');
}

const PREFIX = 'untrusted_local_storage_extension:';

class LocalStorageExt {
getInfo() {
return {
id: 'localstorage',
name: 'Local Storage',
blocks: [
{
opcode: 'load',
blockType: Scratch.BlockType.REPORTER,
text: 'get key [key]',
arguments: {
key: {
type: Scratch.ArgumentType.STRING,
defaultValue: 'example',
},
},
},
{
opcode: 'set',
blockType: Scratch.BlockType.COMMAND,
text: 'set key [key] to [value]',
arguments: {
key: {
type: Scratch.ArgumentType.STRING,
defaultValue: 'example',
},
value: {
type: Scratch.ArgumentType.STRING,
defaultValue: '1234',
},
},
},
GarboMuffin marked this conversation as resolved.
Show resolved Hide resolved
],
};
}
set(args) {
localStorage.setItem(PREFIX + args.key.toString(), JSON.stringify(args.value));
}
load(args) {
try {
const storedValue = localStorage.getItem(PREFIX + args.key.toString());
if (storedValue !== null) {
try {
const parsed = JSON.parse(storedValue);
if (typeof parsed === 'string' || typeof parsed === 'boolean' || typeof parsed === 'number') {
return parsed;
}
} catch (e) {
// JSON.parse failed, ignore
}
// Return the raw value as a string.
return storedValue;
}
} catch (e) {
// localStorage.getItem failed, ignore
}
return '';
}
}
GarboMuffin marked this conversation as resolved.
Show resolved Hide resolved
Scratch.extensions.register(new LocalStorageExt());
})(Scratch);