When a user right-clicks (or long presses) on a block or workspace, a context menu with additional actions is shown. You can configure this context menu to show additional options or to remove the default options. This guide is about adding a custom option to all blocks, or all workspaces. If you want to change the context menu for only one type of block, see the information on the custom blocks page.
Context menu API
The ContextMenuRegistry
class contains methods for registering, unregistering,
and getting all context menu options. The class is a singleton, so methods
should be called on the Blockly.ContextMenuRegistry.registry
object rather
than instantiating a new instance yourself. The ContextMenu
class calls the
getContextMenuItems
method whenever a context menu should be shown. If the
block or workspace has a customContextMenu
function, it is called afterward to
modify the list of options.
Adding custom options
Each menu option in the registry has several properties:
callback
: A function called when the menu option is clicked.scopeType
: One ofBlockly.ContextMenuRegistry.ScopeType.BLOCK
orBlockly.ContextMenuRegistry.ScopeType.WORKSPACE
for where this option should be shown. If an option should be shown for both workspaces and blocks, it should be registered once for each scopeType.displayText
: Either a string or a function that returns a string. Determines the text shown in the menu.preconditionFn
: Function that returns one ofenabled
,disabled
, orhidden
to determine whether and how the menu option should be rendered.weight
: A number that determines the sort order of the option. Options with higher weights appear later in the context menu.id
: A unique string id for the option.
Each of the functions callback
, displayText
(if a function), and
preconditionFn
will be called with a Scope
object that contains information
about the exact workspace or block being clicked on. This way, your context menu
option can reference properties about the workspace or block. For example, the
context menu option that allows a user to delete all blocks says "Delete 42
blocks" if the workspace contains 42 blocks. With the preconditionFn
, a menu
option can be enabled
if some property of the block is true, or disabled
otherwise.
For more examples, you can see the registration of the default context menu options in contextmenu_items.js.
Changing or removing default options
You can unregister any option with
Blockly.ContextMenuRegistry.registry.unregister(id)
. The ids for the default
options are in
contextmenu_items.js.
To change a default option, call getItem
with the id and change it as needed.