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
| Property | Type | Description |
|---|---|---|
id | string | Editor instance ID. |
plugins | Record<string, Plugin> | Map of loaded plugin instances. |
documentBaseURI | URI | URI object for the document base URL. |
baseURI | URI | URI object for the API location. |
contentCSS | string[] | CSS files loaded into the iframe. |
contentStyles | string[] | CSS style strings added to the iframe head. |
ui | EditorUi | Editor UI components (includes ui.registry). |
mode | EditorMode | Editor mode API. |
options | EditorOptions | Editor options API. |
editorUpload | EditorUpload | Editor upload API. |
dom | DOMUtils | DOM utility instance. |
selection | EditorSelection | Selection API instance. |
formatter | Formatter | Formatter API instance. |
undoManager | UndoManager | Undo/redo manager. |
windowManager | WindowManager | Window/dialog manager. |
notificationManager | NotificationManager | Notification manager. |
parser | DomParser | DOM parser instance. |
serializer | DomSerializer | DOM serializer instance. |
schema | Schema | Schema instance. |
shortcuts | Shortcuts | Shortcuts manager. |
annotator | Annotator | Annotator API. |
inline | boolean | True if editor is in inline mode. |
hidden | boolean | True if editor is hidden. |
initialized | boolean | True if editor has been initialized. |
readonly | boolean | True if editor is in readonly mode. |
hasVisual | boolean | Current visual aids state. |
Editor Methods
Initialization & Lifecycle
| Method | Signature | Description |
|---|---|---|
render | () => void | Renders the editor / adds it to the page. |
remove | () => void | Removes the editor from the DOM and the editor42 collection. |
destroy | (automatic?: boolean) => void | Destroys the editor instance, removing all events and references. Called automatically on page unload. |
focus | (skipFocus?: boolean) => void | Focuses the editor. When skipFocus is true, sets as active editor without DOM focus. |
hasFocus | () => boolean | Returns true if the editor has real keyboard focus. |
show | () => void | Shows the editor and hides the replaced textarea/div. |
hide | () => void | Hides the editor and shows the replaced textarea/div. |
isHidden | () => boolean | Returns true if the editor is hidden. |
Content
| Method | Signature | Description |
|---|---|---|
setContent | (content: string, args?: object) => string | Sets content. Also accepts AstNode for tree format. Fires BeforeSetContent/SetContent events. |
getContent | (args?: object) => string | Gets content. Use { format: 'text' } for plain text, { format: 'tree' } for AST node. Fires BeforeGetContent/GetContent events. |
insertContent | (content: string, args?: object) => void | Inserts HTML content at caret position. |
resetContent | (initialContent?: string) => void | Resets content, undo history, and dirty state. If no content specified, resets to initial start content. |
load | (args?: object) => string | Loads content from the original textarea/element. |
save | (args?: object) => string | Saves content back to the original textarea/element. Fires SaveContent event. |
Commands
| Method | Signature | Description |
|---|---|---|
execCommand | (cmd: string, ui?: boolean, value?: any, args?: object) => boolean | Executes a registered command. |
queryCommandState | (cmd: string) => boolean | Returns command-specific state (e.g., whether Bold is active). |
queryCommandValue | (cmd: string) => string | Returns command-specific value (e.g., current FontName). |
queryCommandSupported | (cmd: string) => boolean | Returns true if the command is supported. |
addCommand | (name: string, callback: (ui: boolean, value: any) => boolean | void, scope?: object) => void | Registers a custom command. |
addQueryStateHandler | (name: string, callback: () => boolean, scope?: object) => void | Registers a custom query state handler. |
addQueryValueHandler | (name: string, callback: () => string, scope?: object) => void | Registers a custom query value handler. |
Dirty State
| Method | Signature | Description |
|---|---|---|
isDirty | () => boolean | Returns true if content has been modified since last save or initialization. |
setDirty | (state: boolean) => void | Explicitly sets dirty state. Fires dirty event when changing from clean to dirty. |
DOM Access
| Method | Signature | Description |
|---|---|---|
getContainer | () => HTMLElement | Returns the editor's container element (includes all UI, iframe, etc.). |
getContentAreaContainer | () => HTMLElement | Returns the content area container (holds iframe or editable element). |
getElement | () => HTMLElement | Returns the original textarea/div element that was replaced. |
getWin | () => Window | Returns the iframe's window object. |
getDoc | () => Document | Returns the iframe's document object. |
getBody | () => HTMLElement | Returns the root editable element (iframe's body). |
Editable Root
| Method | Signature | Description |
|---|---|---|
setEditableRoot | (state: boolean) => void | Changes the editable state of the editor's root element. |
hasEditableRoot | () => boolean | Returns the current editable state of the root element. |
Events
| Method | Signature | Description |
|---|---|---|
on | (name: string, callback: Function) => void | Binds an event listener. |
off | (name?: string, callback?: Function) => void | Unbinds event listener(s). |
once | (name: string, callback: Function) => void | Binds a one-time event listener. |
fire | (name: string, args?: object) => object | Fires/dispatches an event (legacy name). |
dispatch | (name: string, args?: object) => object | Fires/dispatches an event. |
hasEventListeners | (name: string) => boolean | Returns true if the event has listeners. |
Miscellaneous
| Method | Signature | Description |
|---|---|---|
nodeChanged | (args?: object) => void | Dispatches NodeChange event to all observers. Call when you need to update UI states. |
translate | (text: string) => string | Translates a string using the language pack. |
hasPlugin | (name: string, loaded?: boolean) => boolean | Checks if a plugin is configured (and optionally loaded). |
convertURL | (url: string, name: string, elm?: string | Element) => string | URL converter function, called when elements with URLs are added. |
addVisual | (elm?: HTMLElement) => void | Adds visual aids for tables, anchors, etc. |
addShortcut | (pattern: string, desc: string, cmdFunc: string | Function, scope?: object) => void | Adds a keyboard shortcut. |
setProgressState | (state: boolean, time?: number) => void | Shows/hides a progress throbber. |
uploadImages | () => Promise<UploadResult[]> | Uploads all data URI/blob URI images to the server. |
getParam | (name: string, defaultVal?: any, type?: string) => any | Returns 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/Method | Signature | Description |
|---|---|---|
data | UndoLevel[] | Array of undo levels. |
typing | boolean | Whether the user is currently typing. |
add | (level?: Partial<UndoLevel>, event?: EditorEvent) => UndoLevel | null | Adds an undo level. |
dispatchChange | () => void | Dispatches a change event. |
beforeChange | () => void | Stores a snapshot before changes. |
undo | () => UndoLevel | undefined | Undoes the last change. |
redo | () => UndoLevel | undefined | Redoes the last undone change. |
clear | () => void | Clears all undo levels. |
reset | () => void | Resets the undo manager. |
hasUndo | () => boolean | Returns true if there are undo levels. |
hasRedo | () => boolean | Returns true if there are redo levels. |
transact | (callback: () => void) => UndoLevel | null | Creates a single undo level from multiple changes. |
ignore | (callback: () => void) => void | Executes changes without creating an undo level. |
extra | (callback1: () => void, callback2: () => void) => UndoLevel | null | Creates 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'