Skip to content

Set and retrieve content

Jiuqing Song edited this page Feb 24, 2018 · 6 revisions

Go back to How to use

Set HTML content

You are able to set initial HTML content of editor via createEditor API or directly create instance of Editor class. Once editor is created, you can still modify the HTML content by some methods of Editor class.

setContent method

To replace whole HTML content with a given HTML string, you can use Editor.setContent() method:

public setContent(content: string);

Once this method is called, all existing content will be replaced, and current cursor position/selection will be reset. And this method will trigger a ContentChanged event with source 'SetContent' and broadcast to all plugins, so that plugins know that whole content is changed, while insertNode() and insertContent() won't trigger such event.

When using insertContent() or setContent(), you need to take the responsibility to make sure the inserted HTML string is clean and safe.

  • Insert/Set HTML with any javascript may cause the script to be executed. So it is better only insert/set HTML content composed by your own code.
  • Insert/Set HTML with global CSS styles may cause CSS bleeding, which may impact HTML elements outside the editor. So it would be better only insert/set HTML content composed by your own code.
  • To do a global CSS to inline CSS converting, you can use convertInlineCss() API from roosterjs-editor-dom package.
function convertInlineCss(
    sourceHtml: string,
    additionalStyleNodes?: HTMLStyleElement[]
): string;

Insert content or node

You can insert HTML content or DOM node into an existing content as well. Please refer to Modify Content section for more details.

Retrieve content

It is always the last action before we dispose editor that we need to retrieve the result HTML content from editor. To retrieve HTML content, Editor class provides some methods: Editor.getContent() and Editor.getTextContent.

Retrieve HTML content

public getContent(triggerExtractContentEvent: boolean = true): string;

By default, this method will return current innerHTML of the editor content DIV.

There is an optional parameter triggerExtractContentEvent and its default value is true. When set to true, editor will broadcast an ExtractContent event to all plugins. Plugins receive this event then they will scan the content to see if there is any temporary content added by plugin, then plugins need to remove those temporary content and return a clean HTML string. So that caller of this method can get clean HTML string without any temporary content.

Retrieve text content

To retrieve text content, you can use Editor.getTextContent() method:

public getTextContent(): string;

This will return the plain text content inside editor without any format information.

More info

Package: roosterjs-editor-core

Support from: 6.0.0 (getTextContent() method requires 6.5.2)

Source code: Editor.ts