Fixed-sized workspace

  • Blockly can be put into a webpage by injecting it into an empty 'div' tag.

  • To set up Blockly, you need to get the code, define an area using a div tag with specified size, and then inject the workspace by defining a toolbox structure and calling Blockly.inject.

  • The workspace variable returned by Blockly.inject will be important later for saving blocks or generating code.

  • If multiple Blockly instances are on a page, each returned workspace should be stored in a different variable.

The simplest way to put Blockly into a webpage is to inject it into an empty 'div' tag.

1. Get the code

Get the code in whatever way works best for your application.

2. Define the area

Add an empty div somewhere in the page's body and set its size:

<div id="blocklyDiv" style="height: 480px; width: 600px;"></div>

3. Inject the workspace

Define the toolbox structure:

const toolbox = {
  "kind": "flyoutToolbox",
  "contents": [
    {
      "kind": "block",
      "type": "controls_if"
    },
    {
      "kind": "block",
      "type": "controls_repeat_ext"
    },
    {
      "kind": "block",
      "type": "logic_compare"
    },
    {
      "kind": "block",
      "type": "math_number"
    },
    {
      "kind": "block",
      "type": "math_arithmetic"
    },
    {
      "kind": "block",
      "type": "text"
    },
    {
      "kind": "block",
      "type": "text_print"
    },
  ]
}

And finally, call the following to inject Blockly into your defined div.

const workspace = Blockly.inject('blocklyDiv', {toolbox: toolbox});

The workspace variable is not currently used, but it will become important later when one wants to save the blocks or generate code. If more than one instance of Blockly is injected onto the same page, ensure that each returned workspace is stored in a different variable.

Now you can test the page in a browser. You should see Blockly's editor filling the div, with seven blocks in the toolbox. Here is a live demo.