Skip to main content

Editor API

Every Editor42 instance exposes a rich API for programmatic control. You can access the active editor or look one up by ID:

// The currently focused editor
const editor = editor42.activeEditor;

// By element ID
const editor = editor42.get('my-editor');

All examples below assume editor holds an Editor42 instance.

Content Methods

setContent / getContent

// Set HTML content
editor.setContent('<p>Hello, world!</p>');

// Get HTML content
const html = editor.getContent();

// Get plain text
const text = editor.getContent({ format: 'text' });

// Get content as AST node tree
const tree = editor.getContent({ format: 'tree' });

setContent fires BeforeSetContent and SetContent events. getContent fires BeforeGetContent and GetContent events.

insertContent

// Insert HTML at the current caret position
editor.insertContent('<img src="logo.png" alt="Logo" />');

resetContent

Resets the editor content, undo history, and dirty state. Pass a string to set new content, or omit it to restore the original content the editor was initialized with.

// Reset to initial content
editor.resetContent();

// Reset with new content
editor.resetContent('<p>Fresh start</p>');

load / save

// Load content from the original textarea/element
editor.load();

// Save content back to the original textarea/element
editor.save();

save fires a SaveContent event.

Command System

Execute built-in or custom commands to apply formatting and trigger editor actions.

// Apply bold
editor.execCommand('Bold');

// Insert horizontal rule
editor.execCommand('InsertHorizontalRule');

// Check if bold is active at the caret
const isBold = editor.queryCommandState('Bold');

// Get current font name
const font = editor.queryCommandValue('FontName');

Custom commands

Register your own commands with addCommand, and optionally provide state and value handlers:

editor.addCommand('myCustomAction', (ui, value) => {
console.log('Custom action fired with value:', value);
});

editor.addQueryStateHandler('myCustomAction', () => {
return editor.dom.getParent(editor.selection.getNode(), '.custom') !== null;
});

editor.addQueryValueHandler('myCustomAction', () => {
return editor.dom.getAttrib(editor.selection.getNode(), 'data-custom');
});

// Execute the custom command
editor.execCommand('myCustomAction', false, 'hello');

State & Dirty Tracking

The dirty flag tracks whether content has changed since the last save or initialization.

// Check if content has been modified
if (editor.isDirty()) {
console.log('Unsaved changes');
}

// Manually mark as dirty or clean
editor.setDirty(true);
editor.setDirty(false);

Setting dirty from false to true fires a dirty event.

DOM Access

Access the editor's internal DOM elements:

// Outer container (includes toolbar, iframe, status bar)
const container = editor.getContainer();

// Content area container (holds the iframe or inline editable)
const contentArea = editor.getContentAreaContainer();

// Original textarea/div that was replaced
const original = editor.getElement();

// Iframe internals
const win = editor.getWin();
const doc = editor.getDoc();
const body = editor.getBody();

Event Handling

Editor42 uses an observable event system. Bindable on any editor instance.

// Listen for content changes
editor.on('change', (e) => {
console.log('Content changed');
});

// One-time listener
editor.once('init', () => {
console.log('Editor initialized');
});

// Remove a specific listener
const handler = (e) => { /* ... */ };
editor.on('NodeChange', handler);
editor.off('NodeChange', handler);

// Dispatch a custom event
editor.dispatch('myCustomEvent', { data: 42 });

// Check if an event has listeners
if (editor.hasEventListeners('change')) {
// ...
}

Keyboard Shortcuts

Register custom keyboard shortcuts using pattern strings. Available modifiers: ctrl, alt, shift, meta, access (maps to Ctrl on Windows/Linux, Ctrl+Option on macOS).

// Bind Ctrl+Alt+O to a command
editor.addShortcut('ctrl+alt+o', 'Open dialog', 'myDialogCommand');

// Bind to a callback function
editor.addShortcut('meta+shift+x', 'Custom action', () => {
console.log('Shortcut triggered');
});

Editor Properties

PropertyTypeDescription
idstringEditor instance ID.
pluginsRecord<string, Plugin>Map of loaded plugin instances.
documentBaseURIURIURI object for the document base URL.
baseURIURIURI object for the API location.
contentCSSstring[]CSS files loaded into the iframe.
contentStylesstring[]CSS style strings added to the iframe head.
uiEditorUiEditor UI components (includes ui.registry).
modeEditorModeEditor mode API.
optionsEditorOptionsEditor options API.
editorUploadEditorUploadEditor upload API.
domDOMUtilsDOM utility instance.
selectionEditorSelectionSelection API instance.
formatterFormatterFormatter API instance.
undoManagerUndoManagerUndo/redo manager.
windowManagerWindowManagerWindow/dialog manager.
notificationManagerNotificationManagerNotification manager.
parserDomParserDOM parser instance.
serializerDomSerializerDOM serializer instance.
schemaSchemaSchema instance.
shortcutsShortcutsShortcuts manager.
annotatorAnnotatorAnnotator API.
inlinebooleanTrue if editor is in inline mode.
hiddenbooleanTrue if editor is hidden.
initializedbooleanTrue if editor has been initialized.
readonlybooleanTrue if editor is in readonly mode.
hasVisualbooleanCurrent visual aids state.

Editor Methods

Initialization & Lifecycle

MethodSignatureDescription
render() => voidRenders the editor / adds it to the page.
remove() => voidRemoves the editor from the DOM and the editor42 collection.
destroy(automatic?: boolean) => voidDestroys the editor instance, removing all events and references. Called automatically on page unload.
focus(skipFocus?: boolean) => voidFocuses the editor. When skipFocus is true, sets as active editor without DOM focus.
hasFocus() => booleanReturns true if the editor has real keyboard focus.
show() => voidShows the editor and hides the replaced textarea/div.
hide() => voidHides the editor and shows the replaced textarea/div.
isHidden() => booleanReturns true if the editor is hidden.

Content

MethodSignatureDescription
setContent(content: string, args?: object) => stringSets content. Also accepts AstNode for tree format. Fires BeforeSetContent/SetContent events.
getContent(args?: object) => stringGets content. Use { format: 'text' } for plain text, { format: 'tree' } for AST node. Fires BeforeGetContent/GetContent events.
insertContent(content: string, args?: object) => voidInserts HTML content at caret position.
resetContent(initialContent?: string) => voidResets content, undo history, and dirty state. If no content specified, resets to initial start content.
load(args?: object) => stringLoads content from the original textarea/element.
save(args?: object) => stringSaves content back to the original textarea/element. Fires SaveContent event.

Commands

MethodSignatureDescription
execCommand(cmd: string, ui?: boolean, value?: any, args?: object) => booleanExecutes a registered command.
queryCommandState(cmd: string) => booleanReturns command-specific state (e.g., whether Bold is active).
queryCommandValue(cmd: string) => stringReturns command-specific value (e.g., current FontName).
queryCommandSupported(cmd: string) => booleanReturns true if the command is supported.
addCommand(name: string, callback: (ui: boolean, value: any) => boolean | void, scope?: object) => voidRegisters a custom command.
addQueryStateHandler(name: string, callback: () => boolean, scope?: object) => voidRegisters a custom query state handler.
addQueryValueHandler(name: string, callback: () => string, scope?: object) => voidRegisters a custom query value handler.

Dirty State

MethodSignatureDescription
isDirty() => booleanReturns true if content has been modified since last save or initialization.
setDirty(state: boolean) => voidExplicitly sets dirty state. Fires dirty event when changing from clean to dirty.

DOM Access

MethodSignatureDescription
getContainer() => HTMLElementReturns the editor's container element (includes all UI, iframe, etc.).
getContentAreaContainer() => HTMLElementReturns the content area container (holds iframe or editable element).
getElement() => HTMLElementReturns the original textarea/div element that was replaced.
getWin() => WindowReturns the iframe's window object.
getDoc() => DocumentReturns the iframe's document object.
getBody() => HTMLElementReturns the root editable element (iframe's body).

Editable Root

MethodSignatureDescription
setEditableRoot(state: boolean) => voidChanges the editable state of the editor's root element.
hasEditableRoot() => booleanReturns the current editable state of the root element.

Events

MethodSignatureDescription
on(name: string, callback: Function) => voidBinds an event listener.
off(name?: string, callback?: Function) => voidUnbinds event listener(s).
once(name: string, callback: Function) => voidBinds a one-time event listener.
fire(name: string, args?: object) => objectFires/dispatches an event (legacy name).
dispatch(name: string, args?: object) => objectFires/dispatches an event.
hasEventListeners(name: string) => booleanReturns true if the event has listeners.

Miscellaneous

MethodSignatureDescription
nodeChanged(args?: object) => voidDispatches NodeChange event to all observers. Call when you need to update UI states.
translate(text: string) => stringTranslates a string using the language pack.
hasPlugin(name: string, loaded?: boolean) => booleanChecks if a plugin is configured (and optionally loaded).
convertURL(url: string, name: string, elm?: string | Element) => stringURL converter function, called when elements with URLs are added.
addVisual(elm?: HTMLElement) => voidAdds visual aids for tables, anchors, etc.
addShortcut(pattern: string, desc: string, cmdFunc: string | Function, scope?: object) => voidAdds a keyboard shortcut.
setProgressState(state: boolean, time?: number) => voidShows/hides a progress throbber.
uploadImages() => Promise<UploadResult[]>Uploads all data URI/blob URI images to the server.
getParam(name: string, defaultVal?: any, type?: string) => anyReturns a configuration parameter by name. Deprecated: use editor.options.get() instead.

UndoManager API

Accessible via editor.undoManager. Manages undo/redo history for the editor.

Property/MethodSignatureDescription
dataUndoLevel[]Array of undo levels.
typingbooleanWhether the user is currently typing.
add(level?: Partial<UndoLevel>, event?: EditorEvent) => UndoLevel | nullAdds an undo level.
dispatchChange() => voidDispatches a change event.
beforeChange() => voidStores a snapshot before changes.
undo() => UndoLevel | undefinedUndoes the last change.
redo() => UndoLevel | undefinedRedoes the last undone change.
clear() => voidClears all undo levels.
reset() => voidResets the undo manager.
hasUndo() => booleanReturns true if there are undo levels.
hasRedo() => booleanReturns true if there are redo levels.
transact(callback: () => void) => UndoLevel | nullCreates a single undo level from multiple changes.
ignore(callback: () => void) => voidExecutes changes without creating an undo level.
extra(callback1: () => void, callback2: () => void) => UndoLevel | nullCreates an extra undo level by first applying callback1, storing it, then applying callback2.

Use transact to batch multiple DOM changes into a single undoable action:

editor.undoManager.transact(() => {
editor.insertContent('<p>Step 1</p>');
editor.insertContent('<p>Step 2</p>');
});
// A single Ctrl+Z will undo both insertions

Use ignore when you need to make changes that should not appear in the undo history:

editor.undoManager.ignore(() => {
editor.dom.addClass(editor.getBody(), 'processing');
});

Editor Mode API

Accessible via editor.mode. Controls whether the editor is editable or read-only.

// Switch to readonly mode
editor.mode.set('readonly');

// Switch back to design (editable) mode
editor.mode.set('design');

// Get the current mode
const currentMode = editor.mode.get(); // 'design' or 'readonly'