Hello, world!
Let's start by creating a very simple extension. This extension just adds a block that reports "Hello, world!":
class HelloWorld {
getInfo() {
return {
id: 'helloworld',
name: 'It works!',
blocks: [
{
opcode: 'hello',
blockType: Scratch.BlockType.REPORTER,
text: 'Hello!'
}
]
};
}
hello() {
return 'World!';
}
}
Scratch.extensions.register(new HelloWorld());
The above is a standard component we will use for showing extension code. Make note of the "Try this extension" button by the title -- that link will let you see what this extension does without having to do anything locally. Note that these extensions are primarily for demonstrating API features; they are not intended to be actually used in projects. There will almost always be another extension on extensions.turbowarp.org that does the same thing, but better.
If you're just using simple files to develop extensions, save this code into a file called "hello-world.js". If you're using a local HTTP server, save the code in a file called "hello-world.js" that the server will let you access.
Now, go to the TurboWarp editor, click on the add extension button (a + next to 2 blocks), scroll to the bottom of the Scratch section, and choose the "Custom Extension" option. Either enter the full URL to your local HTTP server or use one of the other tabs to select your file or paste in code. For now, do not check the "Run extension without sandbox" box.
After a second, an extension named "It works!" should appear in the sidebar. If it doesn't appear, open up your developer tools and look for any warnings in the console. Some of the most common errors are:
- Syntax error in the JavaScript. This should appear in your browser's developer tools.
- Runtime error in the JavaScript. This should appear in your browser's developer tools.
- Your ad blocker or browser is blocking requests to localhost. Try turning off your ad blocker. Once your extension is published on an internet-facing website this shouldn't be a problem.
Now, we will dissect what is going on in this file in the order it runs.
Constructing and registering
class MyExtension {
This is a standard JavaScript class. It is conventional to define your extension in the form of a class. The name of the class doesn't matter, but we suggest making it somehow based on the extension's name. It doesn't have to be unique at this stage.
Scratch.extensions.register(new HelloWorld());
This constructs your class into an object and introduces the special API that allows extensions to function: Scratch. There's a lot on Scratch, but one of the most important functions is Scratch.extensions.register.
Make sure to always call register() exactly once. If you don't call it, your extension will never get added and we will keep waiting for it to load. If you call it multiple times, the behavior is undefined, so don't rely on it.