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
const editor = grapesjs.init({
// options
});
update
Event triggered on any change of the project (eg. component added/removed, style changes, etc.)
editor.on('update', () => { ... });
undo
Undo executed.
editor.on('undo', () => { ... });
redo
Redo executed.
editor.on('redo', () => { ... });
load
Editor is loaded. At this stage, the project is loaded in the editor and elements in the canvas are rendered.
editor.on('load', () => { ... });
project:load
Project JSON loaded in the editor. The event is triggered on the initial load and on theeditor.loadProjectData
method.
editor.on('project:load', ({ project, initial }) => { ... });
project:get
Event 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' });
log
Log message triggered.
editor.on('log', (msg, opts) => { ... });
telemetry:init
Initial telemetry data are sent.
editor.on('telemetry:init', () => { ... });
destroy
Editor started destroy (oneditor.destroy()
).
editor.on('destroy', () => { ... });
destroyed
Editor destroyed.
editor.on('destroyed', () => { ... });
Check the Components module.
Check the Keymaps module.
Check the Style Manager module.
Check the Storage module.
Check the Canvas module.
Check the Rich Text Editor module.
Check the Commands module.
Check the Selectors module.
Check the Blocks module.
Check the Assets module.
Check the Modal module.
Check the Devices module.
Check the Parser module.
Check the Pages module.
Returns configuration object
prop
P?
Returns any Returns the configuration object or the value of the specified property
Returns HTML built inside canvas
-
opts
Object Options (optional, default{}
)opts.component
Component? Return the HTML of a specific Componentopts.cleanId
Boolean Remove unnecessary IDs (eg. those created automatically) (optional, defaultfalse
)
Returns string HTML string
Returns CSS built inside canvas
-
opts
Object Options (optional, default{}
)opts.component
Component? Return the CSS of a specific Componentopts.json
Boolean Return an array of CssRules instead of the CSS string (optional, defaultfalse
)opts.avoidProtected
Boolean Don't include protected CSS (optional, defaultfalse
)opts.onlyMatched
Boolean Return only rules matched by the passed component. (optional, defaultfalse
)opts.keepUnusedStyles
Boolean Force keep all defined rules. Toggle on in case output looks different inside/outside of the editor. (optional, defaultfalse
)
Returns (String | Array<CssRule>) CSS string or array of CssRules
Returns JS of all components
-
opts
Object Options (optional, default{}
)opts.component
Component? Get the JS of a specific component
Returns String JS string
Return the complete tree of components. Use getWrapper
to include also the wrapper
Returns Components
Return the wrapper and its all components
Returns Component
Set components inside editor's canvas. This method overrides actual components
components
(Array<Object> | Object | string) HTML string or components modelopt
Object the options object to be used by the [setComponents]em#setComponents method (optional, default{}
)
editor.setComponents('<div class="cls">New component</div>');
// or
editor.setComponents({
type: 'text',
classes:['cls'],
content: 'New component'
});
Returns this
Add components
-
components
(Array<Object> | Object | string) HTML string or components model -
opts
Object Optionsopts.avoidUpdateStyle
Boolean 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
)
editor.addComponents('<div class="cls">New component</div>');
// or
editor.addComponents({
type: 'text',
classes:['cls'],
content: 'New component'
});
Returns Array<Component>
Returns style in JSON format object
Returns Object
Set style inside editor's canvas. This method overrides actual style
editor.setStyle('.cls{color: red}');
//or
editor.setStyle({
selectors: ['cls'],
style: { color: 'red' }
});
Returns this
Add styles to the editor
editor.addStyle('.cls{color: red}');
Returns Array<CssRule> Array of created CssRule instances
Returns the last selected component, if there is one
Returns Model
Returns an array of all selected components
Returns Array
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 a component
-
el
(Component | HTMLElement) Component to select -
opts
Object? Optionsopts.scroll
Boolean? Scroll canvas to the selected element
// Select dropped block
editor.on('block:drag:stop', function(model) {
editor.select(model);
});
Returns this
Add component to selection
el
(Component | HTMLElement | Array) Component to select
editor.selectAdd(model);
Returns this
Remove component from selection
el
(Component | HTMLElement | Array) Component to select
editor.selectRemove(model);
Returns this
Toggle component selection
el
(Component | HTMLElement | Array) Component to select
editor.selectToggle(model);
Returns this
Returns, if active, the Component enabled in rich text editing mode.
const textComp = editor.getEditing();
if (textComp) {
console.log('HTML: ', textComp.toHTML());
}
Returns (Component | null)
Set device to the editor. If the device exists it will change the canvas to the proper width
name
string Name of the device
editor.setDevice('Tablet');
Returns this
Return the actual active device
var device = editor.getDevice();
console.log(device);
// 'Tablet'
Returns string Device name
Execute command
editor.runCommand('myCommand', {someValue: 1});
Returns any The return is defined by the command
Stop the command if stop method was provided
editor.stopCommand('myCommand', {someValue: 1});
Returns any The return is defined by the command
Store data to the current storage.
This will reset the counter of changes (editor.getDirtyCount()
).
options
Object? Storage options.
const storedData = await editor.store();
Returns Object Stored data.
Load data from the current storage.
-
options
Object? Storage options. -
loadOptions
Object Load options. (optional, default{}
)loadOptions.clear
Boolean Clear the editor state (eg. dirty counter, undo manager, etc.). (optional, defaultfalse
)
const data = await editor.load();
Returns Object Loaded data.
Get the JSON project data, which could be stored and loaded back with editor.loadProjectData(json)
console.log(editor.getProjectData());
// { pages: [...], styles: [...], ... }
Returns Object
Load data from the JSON project
data
Object Project to load
editor.loadProjectData({ pages: [...], styles: [...], ... })
Returns container element. The one which was indicated as 'container' on init method
Returns HTMLElement
Return the count of changes made to the content and not yet stored.
This count resets at any store()
Returns number
Reset the counter of changes.
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
-
opts
{tools: boolean?}? -
options
Object? Optionsoptions.tools
Boolean Update the position of tools (eg. rich text editor, component highlighter, etc.) (optional, defaultfalse
)
Replace the built-in Rich Text Editor with a custom one.
obj
Object Custom RTE Interface
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
}
});
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
parser
(Function | null) Parser function
editor.setCustomParserCss(css => {
const result = [];
// ... parse the CSS string
result.push({
selectors: '.someclass, div .otherclass',
style: { color: 'red' }
})
// ...
return result;
});
Returns this
Change the global drag mode of components. To get more about this feature read: #1936
value
String Drag mode, options: 'absolute' | 'translate'
Returns this
Trigger event log message
-
msg
any Message to log -
opts
Object Custom options (optional, default{}
)
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
Translate label
editor.t('msg');
// use params
editor.t('msg2', { params: { test: 'hello' } });
// custom local
editor.t('msg2', { params: { test: 'hello' } l: 'it' });
Returns String
Attach event
Returns this
Attach event and detach it after the first run
Returns this
Detach event
Returns this
Trigger event
Returns this
Destroy the editor
Render editor
Returns HTMLElement
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.
clb
Function Callback to trigger
editor.onReady(() => {
// perform actions
});
Print safe HTML by using ES6 tagged template strings.
const unsafeStr = '<script>....</script>';
const safeStr = '<b>Hello</b>';
// Use `$${var}` to avoid escaping
const strHtml = editor.html`Escaped ${unsafeStr} unescaped $${safeStr}`;
Returns String