# Editor
Editor contains the top level API which you'll probably use to customize the editor or extend it with plugins. You get the Editor instance on init method and you can pass options via its Configuration Object (opens new window)
const editor = grapesjs.init({
// options
});
# Available Events
updateEvent triggered on any change of the project (eg. component added/removed, style changes, etc.)
editor.on('update', () => { ... });
undoUndo executed.
editor.on('undo', () => { ... });
redoRedo executed.
editor.on('redo', () => { ... });
loadEditor is loaded. At this stage, the project is loaded in the editor and elements in the canvas are rendered.
editor.on('load', () => { ... });
project:loadProject JSON loaded in the editor. The event is triggered on the initial load and on theeditor.loadProjectDatamethod.
editor.on('project:load', ({ project, initial }) => { ... });
project:getEvent triggered on request of the project data. This can be used to extend the project with custom data.
editor.on('project:get', ({ project }) => { project.myCustomKey = 'value' });
logLog message triggered.
editor.on('log', (msg, opts) => { ... });
telemetry:initInitial telemetry data are sent.
editor.on('telemetry:init', () => { ... });
destroyEditor started destroy (oneditor.destroy()).
editor.on('destroy', () => { ... });
destroyedEditor destroyed.
editor.on('destroyed', () => { ... });
# Components
Check the Components module.
# Keymaps
Check the Keymaps module.
# Style Manager
Check the Style Manager module.
# Storage
Check the Storage module.
# Canvas
Check the Canvas module.
# RTE
Check the Rich Text Editor module.
# Commands
Check the Commands module.
# Selectors
Check the Selectors module.
# Blocks
Check the Blocks module.
# Assets
Check the Assets module.
# Modal
Check the Modal module.
# Devices
Check the Devices module.
# Parser
Check the Parser module.
# Pages
Check the Pages module.
# Methods
# getConfig
Returns configuration object
# Parameters
propP?
Returns any Returns the configuration object or the value of the specified property
# getHtml
Returns HTML built inside canvas
# Parameters
optsObject (opens new window) Options (optional, default{})opts.componentComponent? Return the HTML of a specific Componentopts.cleanIdBoolean (opens new window) Remove unnecessary IDs (eg. those created automatically) (optional, defaultfalse)
Returns string (opens new window) HTML string
# getCss
Returns CSS built inside canvas
# Parameters
optsObject (opens new window) Options (optional, default{})opts.componentComponent? Return the CSS of a specific Componentopts.jsonBoolean (opens new window) Return an array of CssRules instead of the CSS string (optional, defaultfalse)opts.avoidProtectedBoolean (opens new window) Don't include protected CSS (optional, defaultfalse)opts.onlyMatchedBoolean (opens new window) Return only rules matched by the passed component. (optional, defaultfalse)opts.keepUnusedStylesBoolean (opens new window) Force keep all defined rules. Toggle on in case output looks different inside/outside of the editor. (optional, defaultfalse)
Returns (String (opens new window) | Array (opens new window)<CssRule>) CSS string or array of CssRules
# getJs
Returns JS of all components
# Parameters
optsObject (opens new window) Options (optional, default{})opts.componentComponent? Get the JS of a specific component
Returns String (opens new window) JS string
# getComponents
Return the complete tree of components. Use getWrapper to include also the wrapper
Returns Components
# getWrapper
Return the wrapper and its all components
Returns Component
# setComponents
Set components inside editor's canvas. This method overrides actual components
# Parameters
components(Array (opens new window)<Object (opens new window)> | Object (opens new window) | string (opens new window)) HTML string or components modeloptObject (opens new window) the options object to be used by the [setComponents]em#setComponents method (optional, default{})
# Examples
editor.setComponents('<div class="cls">New component</div>');
// or
editor.setComponents({
type: 'text',
classes:['cls'],
content: 'New component'
});
Returns this
# addComponents
Add components
# Parameters
components(Array (opens new window)<Object (opens new window)> | Object (opens new window) | string (opens new window)) HTML string or components modeloptsObject (opens new window) Optionsopts.avoidUpdateStyleBoolean (opens new window) If the HTML string contains styles, by default, they will be created and, if already exist, updated. When this option is true, styles already created will not be updated. (optional, defaultfalse)
# Examples
editor.addComponents('<div class="cls">New component</div>');
// or
editor.addComponents({
type: 'text',
classes:['cls'],
content: 'New component'
});
Returns Array (opens new window)<Component>
# getStyle
Returns style in JSON format object
Returns Object (opens new window)
# setStyle
Set style inside editor's canvas. This method overrides actual style
# Parameters
style(Array (opens new window)<Object (opens new window)> | Object (opens new window) | string (opens new window)) CSS string or style modeloptany (optional, default{})
# Examples
editor.setStyle('.cls{color: red}');
//or
editor.setStyle({
selectors: ['cls'],
style: { color: 'red' }
});
Returns this
# addStyle
Add styles to the editor
# Parameters
style(Array (opens new window)<Object (opens new window)> | Object (opens new window) | string (opens new window)) CSS string or style modelopts(optional, default{})
# Examples
editor.addStyle('.cls{color: red}');
Returns Array (opens new window)<CssRule> Array of created CssRule instances
# getSelected
Returns the last selected component, if there is one
Returns Model
# getSelectedAll
Returns an array of all selected components
Returns Array (opens new window)
# getSelectedToStyle
Get a stylable entity from the selected component. If you select a component without classes the entity is the Component itself and all changes will go inside its 'style' attribute. Otherwise, if the selected component has one or more classes, the function will return the corresponding CSS Rule
Returns Model
# select
Select a component
# Parameters
el(Component | HTMLElement (opens new window)) Component to selectoptsObject (opens new window)? Optionsopts.scrollBoolean (opens new window)? Scroll canvas to the selected element
# Examples
// Select dropped block
editor.on('block:drag:stop', function(model) {
editor.select(model);
});
Returns this
# selectAdd
Add component to selection
# Parameters
el(Component | HTMLElement (opens new window) | Array (opens new window)) Component to select
# Examples
editor.selectAdd(model);
Returns this
# selectRemove
Remove component from selection
# Parameters
el(Component | HTMLElement (opens new window) | Array (opens new window)) Component to select
# Examples
editor.selectRemove(model);
Returns this
# selectToggle
Toggle component selection
# Parameters
el(Component | HTMLElement (opens new window) | Array (opens new window)) Component to select
# Examples
editor.selectToggle(model);
Returns this
# getEditing
Returns, if active, the Component enabled in rich text editing mode.
# Examples
const textComp = editor.getEditing();
if (textComp) {
console.log('HTML: ', textComp.toHTML());
}
Returns (Component | null)
# setDevice
Set device to the editor. If the device exists it will change the canvas to the proper width
# Parameters
namestring (opens new window) Name of the device
# Examples
editor.setDevice('Tablet');
Returns this
# getDevice
Return the actual active device
# Examples
var device = editor.getDevice();
console.log(device);
// 'Tablet'
Returns string (opens new window) Device name
# runCommand
Execute command
# Parameters
idstring (opens new window) Command IDoptionsObject (opens new window) Custom options (optional, default{})
# Examples
editor.runCommand('myCommand', {someValue: 1});
Returns any The return is defined by the command
# stopCommand
Stop the command if stop method was provided
# Parameters
idstring (opens new window) Command IDoptionsObject (opens new window) Custom options (optional, default{})
# Examples
editor.stopCommand('myCommand', {someValue: 1});
Returns any The return is defined by the command
# store
Store data to the current storage.
This will reset the counter of changes (editor.getDirtyCount()).
# Parameters
optionsObject (opens new window)? Storage options.
# Examples
const storedData = await editor.store();
Returns Object (opens new window) Stored data.
# load
Load data from the current storage.
# Parameters
optionsObject (opens new window)? Storage options.loadOptionsObject (opens new window) Load options. (optional, default{})loadOptions.clearBoolean (opens new window) Clear the editor state (eg. dirty counter, undo manager, etc.). (optional, defaultfalse)
# Examples
const data = await editor.load();
Returns Object (opens new window) Loaded data.
# getProjectData
Get the JSON project data, which could be stored and loaded back with editor.loadProjectData(json)
# Examples
console.log(editor.getProjectData());
// { pages: [...], styles: [...], ... }
Returns Object (opens new window)
# loadProjectData
Load data from the JSON project
# Parameters
dataObject (opens new window) Project to load
# Examples
editor.loadProjectData({ pages: [...], styles: [...], ... })
# getContainer
Returns container element. The one which was indicated as 'container' on init method
Returns HTMLElement (opens new window)
# getDirtyCount
Return the count of changes made to the content and not yet stored.
This count resets at any store()
Returns number (opens new window)
# clearDirtyCount
Reset the counter of changes.
# refresh
Update editor dimension offsets
This method could be useful when you update, for example, some position of the editor element (eg. canvas, panels, etc.) with CSS, where without refresh you'll get misleading position of tools
# Parameters
opts{tools: boolean (opens new window)?}?optionsObject (opens new window)? Optionsoptions.toolsBoolean (opens new window) Update the position of tools (eg. rich text editor, component highlighter, etc.) (optional, defaultfalse)
# setCustomRte
Replace the built-in Rich Text Editor with a custom one.
# Parameters
objObject (opens new window) Custom RTE Interface
# Examples
editor.setCustomRte({
// Function for enabling custom RTE
// el is the HTMLElement of the double clicked Text Component
// rte is the same instance you have returned the first time you call
// enable(). This is useful if need to check if the RTE is already enabled so
// ion this case you'll need to return the RTE and the end of the function
enable: function(el, rte) {
rte = new MyCustomRte(el, {}); // this depends on the Custom RTE API
...
return rte; // return the RTE instance
}
// Disable the editor, called for example when you unfocus the Text Component
disable: function(el, rte) {
rte.blur(); // this depends on the Custom RTE API
}
// Called when the Text Component is focused again. If you returned the RTE instance
// from the enable function, the enable won't be called again instead will call focus,
// in this case to avoid double binding of the editor
focus: function (el, rte) {
rte.focus(); // this depends on the Custom RTE API
}
});
# setCustomParserCss
Replace the default CSS parser with a custom one.
The parser function receives a CSS string as a parameter and expects
an array of CSSRule objects as a result. If you need to remove the
custom parser, pass null as the argument
# Parameters
parser(Function (opens new window) | null) Parser function
# Examples
editor.setCustomParserCss(css => {
const result = [];
// ... parse the CSS string
result.push({
selectors: '.someclass, div .otherclass',
style: { color: 'red' }
})
// ...
return result;
});
Returns this
# setDragMode
Change the global drag mode of components. To get more about this feature read: https://github.com/GrapesJS/grapesjs/issues/1936 (opens new window)
# Parameters
valueString (opens new window) Drag mode, options: 'absolute' | 'translate'
Returns this
# log
Trigger event log message
# Parameters
msgany Message to logoptsObject (opens new window) Custom options (optional, default{})opts.nsString (opens new window) Namespace of the log (eg. to use in plugins) (optional, default'')opts.levelString (opens new window) Level of the log,debug,info,warning,error(optional, default'debug')
# Examples
editor.log('Something done!', { ns: 'from-plugin-x', level: 'info' });
// This will trigger following events
// `log`, `log:info`, `log-from-plugin-x`, `log-from-plugin-x:info`
// Callbacks of those events will always receive the message and
// options, as arguments, eg:
// editor.on('log:info', (msg, opts) => console.info(msg, opts))
Returns this
# t
Translate label
# Parameters
args...Array (opens new window)<any>keyString (opens new window) Label to translateoptsObject (opens new window)? Options for the translationopts.paramsObject (opens new window)? Params for the translationopts.noWarnBoolean (opens new window)? Avoid warnings in case of missing resources
# Examples
editor.t('msg');
// use params
editor.t('msg2', { params: { test: 'hello' } });
// custom local
editor.t('msg2', { params: { test: 'hello' } l: 'it' });
Returns String (opens new window)
# on
Attach event
# Parameters
eventstring (opens new window) Event namecallbackFunction (opens new window) Callback function
Returns this
# once
Attach event and detach it after the first run
# Parameters
eventstring (opens new window) Event namecallbackFunction (opens new window) Callback function
Returns this
# off
Detach event
# Parameters
eventstring (opens new window) Event namecallbackFunction (opens new window) Callback function
Returns this
# trigger
Trigger event
# Parameters
eventstring (opens new window) Event to triggerargs...Array (opens new window)<any>
Returns this
# destroy
Destroy the editor
# render
Render editor
Returns HTMLElement (opens new window)
# onReady
Trigger a callback once the editor is loaded and rendered. The callback will be executed immediately if the method is called on the already rendered editor.
# Parameters
clbFunction (opens new window) Callback to trigger
# Examples
editor.onReady(() => {
// perform actions
});
# html
Print safe HTML by using ES6 tagged template strings.
# Parameters
literalsArray (opens new window)<String (opens new window)>substsArray (opens new window)<String (opens new window)>
# Examples
const unsafeStr = '<script>....</script>';
const safeStr = '<b>Hello</b>';
// Use `$${var}` to avoid escaping
const strHtml = editor.html`Escaped ${unsafeStr} unescaped $${safeStr}`;
Returns String (opens new window)
← API Reference I18n →