Skip to main content

Customizing context menus

8. Display text

So far the displayText has always been a simple string, but it can also be HTML, or a function that returns either of the former. Using a function can be useful when you want a context-dependent message.

When defined as a function displayText accepts a scope argument, just like callback and preconditionFn.

As an example, add this registry item. The display text depends on the block type.

function registerDisplayItem() {
const displayItem = {
displayText: function (scope) {
if (scope.focusedNode.type.startsWith('text')) {
return 'Text block';
} else if (scope.focusedNode.type.startsWith('controls')) {
return 'Controls block';
} else {
return 'Some other block';
}
},
preconditionFn: function (scope) {
return scope.focusedNode instanceof Blockly.BlockSvg
? 'enabled'
: 'hidden';
},
callback: function (scope) {},
id: 'display_text_example',
weight: 100,
};
Blockly.ContextMenuRegistry.registry.register(displayItem);
}

As usual, remember to call registerDisplayItem() from your start function.

Test it

  • Reload the workspace and open context menus on various blocks.
  • The last context menu option's text should vary based on the block type.