Repository navigation
Plugins
A plugin is a JavaScript file that the editor loads at start-up and that receives the editor instance through Draw.loadPlugin. This page is for developers who want to add actions, menus, panels or behaviour to a running editor without changing its source: a step-by-step first plugin, the rules for how plugins are loaded, the plugins in this repository, and tested recipes. For changing the editor itself, see Extending the editor.
This takes about five minutes and needs nothing but a local copy of the repository (see Getting started).
1. Serve the editor.
cd src/main/webapp
python3 -m http.server 80802. Allow custom plugins. Add this line to the end of src/main/webapp/js/PreConfig.js:
window.ALLOW_CUSTOM_PLUGINS = true;Without it, the editor only loads the plugins listed in its built-in registry. PreConfig.js is loaded in development mode (?dev=1) and, in production mode, on every host except *.draw.io and *.diagrams.net, so this works on localhost and on your own server.
3. Create src/main/webapp/plugins/hello.js:
Draw.loadPlugin(function(ui)
{
var graph = ui.editor.graph;
// Label for the action (the action name is the resource key)
mxResources.parse('helloWorld=Hello World');
ui.actions.addAction('helloWorld', function()
{
ui.alert('Selected cells: ' + graph.getSelectionCount());
});
// Appends the action to the end of the Extras menu
ui.menus.addPluginMenuItems('extras', ['helloWorld']);
});4. Register the plugin in your browser. Open http://localhost:8080/, open the browser's developer console and run:
mxSettings.setPlugins(mxSettings.getPlugins().concat(['plugins/hello.js']));
mxSettings.save();This adds the path to the plugin list in the editor settings (stored in localStorage under .drawio-config for this origin). Reload the page.
5. See it work. Open Extras > Hello World and click it. In the simple theme (?ui=simple), the Extras menu is Settings in the main menu. Extras > Plugins now lists plugins/hello.js; delete it there (then Apply and reload) to unload it.
6. Iterate. Edit hello.js and reload with the cache disabled (in the developer tools, Network > Disable cache). A normal reload can run a cached copy of the plugin. Exceptions thrown by a queued callback are caught and logged to the console as Plugin Error:; other errors show up in the console as usual. Use ?dev=1 if you also want to step through the editor's own sources (see Debugging).
From here, the recipes below show the common extension points.
flowchart LR
P["?p=id1;id2<br/>(registry ids)"] --> S[mxscript]
L["Plugin list in settings<br/>(Extras > Plugins)"] -->|"same origin, and built-in<br/>or ALLOW_CUSTOM_PLUGINS"| S
S --> D["Draw.loadPlugin(fn)"]
D -->|"before the UI exists"| Q["App.DrawPlugins queue"]
Q -->|"App constructor"| R["fn(ui)"]
D -->|"after start-up"| R
App.main (App.js) calls App.initPluginCallback(), which defines the global Draw.loadPlugin. Callbacks registered before the UI exists are queued; the App constructor runs them with the new App instance (an EditorUi) right after the UI is built and before the first diagram is loaded, then replaces Draw.loadPlugin so that later callbacks run immediately. Draw.loadPlugin is the only supported entry point to the editor instance; there is no global variable for it.
| Source | How to use it | Rules |
|---|---|---|
p URL parameter |
?p=sql;anon |
Only ids in App.pluginRegistry, separated by ;. Unknown ids are logged as Unknown plugin:. The file is loaded from PLUGINS_BASE_PATH + the registered path (default: relative to the page). Applies to this page load only. |
| Plugins dialog | Extras > Plugins in the classic theme; in the simple, sketch and min themes the Plugins button of Settings > Configuration | Offers the plugins in App.publicPlugin. Stores their paths (for example plugins/sql.js) in the user's settings (mxSettings, localStorage key .drawio-config). Takes effect after a reload. Only shown when localStorage is available. |
| Custom entries in the same list | Any path or URL added to the settings, as in the tutorial | Loaded only if the URL has the same protocol and host as the editor (App.isSameDomain, otherwise Blocked plugin:), and only if it is a built-in plugin or window.ALLOW_CUSTOM_PLUGINS is true (otherwise Unknown plugin:). An entry starting with / is prefixed with PLUGINS_BASE_PATH. |
js/PostConfig.js on a self-hosted instance |
See Loading a plugin for every user | Runs for every user of the deployment. |
Things that switch plugins off:
-
plugins=0oroffline=1in the URL load no plugins (App.main). -
embedInline=1setsplugins=0(Init.js).
There is no plugins key in the editor configuration (Editor.configure, DRAWIO_CONFIG). The configuration can only hide the menu item, with "hideMenuItems": ["plugins"] (see configure-diagram-editor).
Retired plugins are mapped to the built-in feature that replaced them (App.retiredPlugins, App.applyRetiredPlugin): p=tips and a saved plugins/tooltips.js turn on the built-in tooltip icons instead of loading a file.
- In embed mode, the editor waits until all plugins have loaded, or at most five seconds, before it sends the
initmessage to the host (App.embedModePluginsCount,App.prototype.initializeEmbedMode). To give an embedded editor a plugin, addpto the iframe URL; plugins saved in the user's settings for the editor's origin are loaded as well, also withconfigure=1. See Embedding. - Plugins also run in the lightbox and other chromeless views (
lightbox=1,chrome=0, viewer.diagrams.net). Thereui.menubar,ui.sidebar,ui.formatandui.toolbararenull; checkui.editor.isChromelessView()or test fornull.props.jsandexplore.jsshow how a plugin changes click behaviour in the lightbox. - The viewer library (
viewer.min.js,viewer-static.min.js) has noDraw.loadPlugin; plugins are part of the full editor only.
Since drawio-desktop 31.1.5 the desktop app no longer loads external plugin files (the former --enable-plugins option was removed). Its Plugins dialog only offers the built-in plugins in App.publicPlugin, which are loaded from the plugins folder bundled with the app; saved entries outside that folder or containing .. are skipped, and the web loading described above is switched off (ElectronApp.js sets plugins=0). See Desktop app.
To load a plugin for all users of a self-hosted instance, without asking each user to add it:
// src/main/webapp/js/PostConfig.js
App.initPluginCallback();
mxscript('plugins/hello.js');PostConfig.js runs after the application code has loaded and is requested on the same hosts as PreConfig.js. App.initPluginCallback() creates the plugin queue if App.main has not done so yet, so Draw.loadPlugin in the plugin file works whichever runs first. Plugins loaded this way ignore plugins=0. In a fork you can instead add an id to App.pluginRegistry (and to App.publicPlugin to offer it in the Plugins dialog), which requires rebuilding app.min.js (see Building).
The files are in src/main/webapp/plugins. They are maintained as examples rather than as supported features, and several of them have been superseded by built-in features (see the plugin list on drawio.com).
p id |
File | What it does |
|---|---|---|
ex |
explore.js |
Adds Explore from here to the context menu of connected cells; in the lightbox, clicking a connected shape explores from it. |
svgdata |
svgdata.js |
SVG export in the legacy metadata format: data-* attributes and a <g id="cell-..."> group per cell. |
number |
number.js |
Numbers vertices with a badge, toggled with View > Number; adds a Numbered style property. |
sql |
sql.js |
Adds From SQL to the Insert menu: a window that turns CREATE TABLE statements into table shapes. |
props |
props.js |
Shows the data (attributes) of the selected cell: Extras > Extract Data in the editor, a floating panel in the lightbox. |
text |
text.js |
Adds the built-in Extract Text action to the Extras menu. |
anim |
animation.js |
Adds the built-in Animation action to the Extras menu. |
update |
update.js |
Data-driven diagrams: posts the page XML to a URL at an interval and applies the cell updates in the response. Configured with updateUrl/updateInterval in the diagram's data or the update-url/update-interval URL parameters. |
trees |
trees/trees.js |
Tree and mind map editing: select children, siblings, parent and subtree actions, keyboard navigation, and a Trees palette. |
import |
import.js |
Imports Freemind (.mm) files through an Import menu in the classic menu bar. |
replay |
replay.js |
Extras > Record and Replay: records the changes made to a diagram and replays them in a new window. |
anon |
anonymize.js |
Extras > Anonymize Current Page: scrambles the labels, data and name of the current page. |
tr |
trello.js |
Glue for the Trello integration; only does something in embed mode. |
f5 |
rackF5.js |
F5 rack shapes registered with mxCellRenderer.registerShape and a Rack / F5 v2 palette. |
webcola |
webcola/webcola.js |
Layout > WebCola Layout (constraint-based layout). Marked deprecated in the file in favour of the built-in ELK layouts. |
rnd |
random.js |
Test helpers: random labels and random reordering, swapping and placing of children. |
page |
page.js |
Test helpers that randomly reorder, insert and remove pages. |
tags |
tags.js |
Extras > Hidden Tags: a window to tag cells and hide cells by tag. |
nxtcld |
nextcloud.js |
Glue for the Nextcloud integration (embed mode). |
edgeConnection.js (drops a small circle when a new edge ends in free space) and flow.js (Toggle Flow on edges, animated in the lightbox) are not in the registry; load them as custom entries (plugins/flow.js) with ALLOW_CUSTOM_PLUGINS. A few registry ids point to files for hosted integrations that are not part of this repository and fail to load here; 4xAKTrabTpTzahoLthkwPNUn is a legacy alias of ex.
App.publicPlugin (the list offered in the Plugins dialog) contains ex, svgdata, number, sql, props, text, anim, update, trees, replay, anon, webcola and tags.
/**
* Example plugin: one line on what it does.
*/
Draw.loadPlugin(function(ui)
{
var editor = ui.editor; // Editor
var graph = editor.graph; // Graph (extends mxGraph)
var model = graph.getModel();
// UI strings: the action name is the resource key
mxResources.parse('myAction=My Action');
ui.actions.addAction('myAction', function()
{
model.beginUpdate();
try
{
// change the model here (one undoable step)
}
finally
{
model.endUpdate();
}
});
// The menu bar, sidebar, format panel and toolbar do not exist
// in chromeless views (lightbox, chrome=0)
if (ui.menus != null && !editor.isChromelessView())
{
ui.menus.addPluginMenuItems('extras', ['myAction']);
}
// The callback runs before the first diagram is loaded, unless
// the plugin file finished loading after start-up
editor.addListener('fileLoaded', function()
{
// a diagram was opened (not fired in embed mode)
});
});The objects you will use most:
| Expression | Class | Source |
|---|---|---|
ui |
App (extends EditorUi) |
diagramly/App.js, grapheditor/EditorUi.js, diagramly/EditorUi.js
|
ui.editor |
Editor |
grapheditor/Editor.js, diagramly/Editor.js
|
ui.editor.graph |
Graph |
grapheditor/Graph.js |
graph.getModel() |
mxGraphModel |
mxgraph/src/model/mxGraphModel.js |
ui.actions, ui.menus
|
Actions, Menus
|
grapheditor/Actions.js, grapheditor/Menus.js, diagramly/Menus.js
|
ui.sidebar, ui.format, ui.toolbar
|
Sidebar, Format, Toolbar
|
grapheditor/Sidebar.js, grapheditor/Format.js, grapheditor/Toolbar.js
|
ui.keyHandler |
mxKeyHandler |
EditorUi.prototype.createKeyHandler |
ui.getCurrentFile() |
DrawioFile subclass |
diagramly/DrawioFile.js |
How these fit together is described in Architecture and Extending the editor; the model API in Graph model.
Each recipe was run against the current release. They go inside the Draw.loadPlugin callback, with graph = ui.editor.graph.
mxResources.parse('markReviewed=Mark as Reviewed');
var action = ui.actions.addAction('markReviewed', function()
{
// ...
}, null, null, Editor.ctrlKey + '+Shift+X');
ui.menus.addPluginMenuItems('extras', ['-', 'markReviewed']);-
Actions.prototype.addAction(key, funct, enabled, iconCls, shortcut, visible)returns theAction. A key ending in...(for example'reviewNote...') is registered without the dots and shown with them, the convention for actions that open a dialog. -
The fifth argument is only the text shown next to the menu item; binding the key is a separate step (next recipe).
-
Menus.prototype.addPluginMenuItems(menuName, items)appends action names (or'-'for a separator) to a named menu:'file','edit','view','arrange','insert','layout','extras','help'and others. The items appear in every theme, including the classic menu bar and the main menu of the simple theme. It exists since 29.6.2; before 31.5.3 the items did not show in the classic menu bar. -
The bundled plugins use the older pattern, which also works and lets you choose the position:
var menu = ui.menus.get('extras'); var oldFunct = menu.funct; menu.funct = function(menu, parent) { oldFunct.apply(this, arguments); ui.menus.addMenuItems(menu, ['-', 'markReviewed'], parent); };
// Ctrl+Shift+X (Cmd+Shift+X on macOS): code, control, action name, shift
ui.keyHandler.bindAction(88, true, 'markReviewed', true);
// Alt+Shift+K
ui.altShiftActions[75] = 'markReviewed';keyHandler.bindAction(code, control, key, shift) looks the action up when you call it, so add the action first; a key bound this way runs the action only while it is enabled. EditorUi.prototype.altShiftActions, ctrlAltShiftActions, ctrlAltActions and altActions map key codes to action names, are resolved on each key press and do not check the enabled state. Check for conflicts with existing bindings and with the browser's own shortcuts. Deployments can also rebind keys without code through the keyboardShortcuts configuration key.
var createPopupMenu = ui.menus.createPopupMenu;
ui.menus.createPopupMenu = function(menu, cell, evt)
{
createPopupMenu.apply(this, arguments);
if (!graph.isSelectionEmpty())
{
this.addMenuItems(menu, ['-', 'markReviewed'], null, evt);
}
};Menus.prototype.createPopupMenu(menu, cell, evt) builds the context menu each time it opens; explore.js and flow.js use this pattern.
if (ui.toolbar != null)
{
ui.toolbar.addSeparator();
ui.toolbar.addItems(['markReviewed'], null, null, [Editor.checkmarkImage]);
}Toolbar.prototype.addItems(keys, container, noListeners, icons, minWidth) adds a button per action that follows the action's enabled state. The icon must be a data: URI (EditorUi.prototype.createToolbarButton ignores other values); the Editor.*Image constants are data URIs you can reuse. This toolbar is only visible in the classic theme. The simple and sketch themes build their own compact toolbars in Simple.js without an extension point, so add a menu item as well.
action.setEnabled(false);
graph.getSelectionModel().addListener(mxEvent.CHANGE, function(sender, evt)
{
action.setEnabled(!graph.isSelectionEmpty());
});Disabled actions are disabled in the toolbar and greyed out or left out in menus, depending on the menu. evt.getProperty('added') and evt.getProperty('removed') hold the changed cells. Note that in mxGraph the names are swapped: added holds the cells that were deselected and removed the cells that were selected (see the comment in mxGraphSelectionModel). graph.getSelectionCells() is usually what you want.
graph.getModel().addListener(mxEvent.CHANGE, function(sender, evt)
{
var changes = evt.getProperty('edit').changes;
for (var i = 0; i < changes.length; i++)
{
if (changes[i] instanceof mxValueChange)
{
// changes[i].cell, changes[i].value, changes[i].previous
}
}
});The event fires once per endUpdate of the outermost beginUpdate, also for undo and redo and for changes applied by other code, such as edits from collaborators. The change classes are mxChildChange, mxTerminalChange, mxValueChange, mxStyleChange, mxGeometryChange, mxCollapseChange, mxVisibleChange, mxCellAttributeChange and mxRootChange in mxGraphModel.js, plus draw.io's page changes. Do not change the model from inside this listener. To know when a diagram is opened, listen to fileLoaded on ui.editor; for page switches, pageSelected on ui.editor.
var cells = graph.getSelectionCells();
graph.getModel().beginUpdate();
try
{
for (var i = 0; i < cells.length; i++)
{
graph.setAttributeForCell(cells[i], 'reviewed', '1');
}
}
finally
{
graph.getModel().endUpdate();
}
var reviewed = graph.getAttributeForCell(cell, 'reviewed', '0');setAttributeForCell(cell, name, value) turns a plain string value into a UserObject element (the old value becomes its label attribute) and sets the attribute; null removes it. The result is saved in the file as <UserObject label="..." reviewed="1" id="..."> and shown in Edit Data (Ctrl+M). Attributes can be used as placeholders in labels (see placeholders). Use a style key instead (graph.setCellStyles(key, value, cells)) for values that should affect rendering. See Graph model for user objects.
if (ui.sidebar != null)
{
var sb = ui.sidebar;
function addPalette()
{
sb.addPaletteFunctions('myShapes', 'My Shapes', true,
[
sb.createVertexTemplateEntry('rounded=1;whiteSpace=wrap;html=1;' +
'fillColor=#dae8fc;strokeColor=#6c8ebf;', 120, 60, 'Service',
'Service', null, null, 'service component'),
sb.createVertexTemplateEntry('shape=cylinder3;whiteSpace=wrap;' +
'html=1;boundedLbl=1;size=15;', 60, 80, 'DB', 'Database',
null, null, 'database storage'),
sb.createEdgeTemplateEntry('endArrow=classic;html=1;', 100, 0,
'', 'Call', null, 'call arrow')
]);
};
addPalette();
// The sidebar is rebuilt when the language changes: add it again
var sidebarInit = sb.init;
sb.init = function()
{
sidebarInit.apply(this, arguments);
addPalette();
};
}The palette is appended at the end of the sidebar and its entries are added to the shape search. createVertexTemplateEntry(style, width, height, value, title, showLabel, showTitle, tags) and createEdgeTemplateEntry(style, width, height, value, title, showLabel, tags) take a style string (Styles); createVertexTemplateFromCells takes prepared cells (see trees.js). Sidebar.prototype.refresh, which runs on languageChanged and sidebarTitlesChanged, calls init again and drops palettes added by plugins, hence the wrapper (the same pattern as trees.js). More in Extending the editor.
mxResources.parse('reviewNote=Review Note');
ui.actions.addAction('reviewNote...', function()
{
var cell = graph.getSelectionCell();
if (cell == null)
{
return;
}
var div = document.createElement('div');
var title = document.createElement('h3');
mxUtils.write(title, mxResources.get('reviewNote'));
div.appendChild(title);
var input = document.createElement('input');
input.setAttribute('type', 'text');
input.style.width = '100%';
input.style.boxSizing = 'border-box';
input.value = graph.getAttributeForCell(cell, 'reviewNote', '');
div.appendChild(input);
var dlg = new CustomDialog(ui, div, function()
{
graph.setAttributeForCell(cell, 'reviewNote', input.value);
});
ui.showDialog(dlg.container, 320, null, true, true);
input.focus();
});CustomDialog(editorUi, content, okFn, cancelFn, okButtonText, ...) adds the OK and Cancel buttons; passing null as the height to EditorUi.prototype.showDialog(elt, w, h, modal, closable, ...) sizes the dialog to its content. Write user and diagram text with mxUtils.write or textContent, never innerHTML. For simple cases use ui.alert(msg), ui.confirm(msg, okFn, cancelFn) or ui.prompt(title, defaultValue, fn); for a floating panel, mxWindow (see props.js and tags.js). The dialog style guide lists the CSS classes for consistent dialogs.
var styleFormatPanelInit = StyleFormatPanel.prototype.init;
StyleFormatPanel.prototype.init = function()
{
styleFormatPanelInit.apply(this, arguments);
var cells = this.editorUi.getSelectionState().cells;
if (cells.length == 1)
{
var g = this.editorUi.editor.graph;
var panel = this.createPanel();
panel.appendChild(this.createTitle('Review'));
var status = document.createElement('div');
mxUtils.write(status, (g.getAttributeForCell(cells[0],
'reviewed') == '1') ? 'Reviewed' : 'Not reviewed');
panel.appendChild(status);
this.container.appendChild(panel);
}
};The format panel creates new panel objects on every refresh (after selection and model changes), so overriding the init of StyleFormatPanel, TextFormatPanel, ArrangePanel or DiagramFormatPanel adds the section each time. To add a single property to the Property table of the Style tab instead, push a definition to Editor.commonVertexProperties or Editor.commonEdgeProperties, as number.js does (Editor.commonProperties is copied into both when the code loads, so adding to it later has no effect). See Extending the editor.
draw.io has no versioned plugin API. Apart from Draw.loadPlugin, plugins call the same internal classes and functions as the editor itself, and these change between releases without notice. Keep plugins small, wrap functions rather than copying them, guard against missing objects (ui.sidebar, ui.toolbar) and test your plugins against each release before you update a self-hosted instance. The plugins in this repository ship with each release and are a good reference for patterns that work in it.
A plugin is an ordinary script in the editor page and runs with the full privileges of the page: it can read and change every diagram the user opens, use the user's signed-in storage connections, and send data anywhere the page's content security policy allows. Only load plugins you have reviewed like your own code, and keep ALLOW_CUSTOM_PLUGINS off unless you control every script that can be served from the editor's origin. Plugins that render diagram content (labels, attributes, links) as HTML must sanitise it with Graph.sanitizeHtml; see Security.
Describes the dev branch of jgraph/drawio as of release 32.3.0 (October 2026). Internal JavaScript APIs change between releases; check the code of the version you use. · Questions: Discussions · Bugs: Issues · Vulnerabilities: report privately · User docs: drawio.com/docs
Get started
Concepts
Guides
- Self-hosting
- Configuration
- Storage backends
- OneDrive app registration
- Embedding
- Diagrams in GitHub
- Plugins
- Extending the editor
- Shapes and stencils
- Import and export
- Desktop app
- Internationalization
Reference
Project
Elsewhere