Custom blocks without having a DOM

94 views
Skip to first unread message

ArM

unread,
Dec 17, 2022, 3:50:31 PM12/17/22
to Blockly
I am working on a project that allows converting serialized workspaces into javascript. The project doesn't have an UI. I created a dynamic workspace, loaded the serialized workspace and here the problem begins. When I create cusom blocks and append them to Blockly.Blocks object, an error is thrown that says I can't use .appendChild(). Is there any way to create blocks and append code generators to them without having a workspace injected into a DOM element?

Aaron Dodson

unread,
Dec 19, 2022, 11:21:58 AM12/19/22
to Blockly
Hi,

This usecase should indeed be supported; to clarify, when you say you're appending your custom blocks to Blockly.Blocks, are you doing so by calling Blockly.Blocks.appendChild(yourblock), or are you doing Blockly.Blocks['block_name'] = {block definition}/Blockly.defineBlocksWithJsonArray([{block definition}], and seeing that appendChild is being called from somewhere in Blockly's internals?

- Aaron

ArM

unread,
Dec 19, 2022, 11:32:15 AM12/19/22
to Blockly
Hello Aaron and thanks to your reply

When I append blocks I use the second option (Blockly.Blocks['block'] = block). Also, appendChild is called in Blockly's internals, and throws the following error: Uncaught (in promise) TypeError: Cannot read properties of undefined (reading 'appendChild')

ArM

unread,
Dec 20, 2022, 10:00:43 AM12/20/22
to Blockly
To make things more clear, I attached some images with the error
Untitled.png
Untitled2.png

Aaron Dodson

unread,
Dec 20, 2022, 11:26:44 AM12/20/22
to Blockly
Thanks for the additional info! I notice that the stack trace is calling various methods in BlockSvg as opposed to Block - to double check, how are you creating your workspace?

- Aaron

ArM

unread,
Dec 20, 2022, 11:58:04 AM12/20/22
to Blockly
I use Blockly.WorkspaceSvg()

Aaron Dodson

unread,
Dec 20, 2022, 12:00:27 PM12/20/22
to Blockly
Ah, that's the issue - the *Svg classes are intended for rendering/display. When using Blockly in headless mode or an environment without a DOM, creating the workspace using new Workspace() will give you a Workspace object that doesn't depend on the DOM being present.

- Aaron

ArM

unread,
Dec 20, 2022, 12:23:05 PM12/20/22
to Blockly
thanks for your answer, it really worked! Blockly docs confused me, as they said I should use WorkspaceSvg
Reply all
Reply to author
Forward
0 new messages