I’m currently working with the RoosterJS rich text editor in my project, and I need to set the HTML content programmatically. My goal is to replace the entire content of the editor with a new HTML string.
I’ve gone through the RoosterJS documentation and explored the source code. I found a method called setContent in the source code on GitHub, which seems to do exactly what I need. However, it appears that this method is not included in the package( roosterjs: 9.9.1) I’m using.
Is there an alternative method or recommended approach to set or replace the entire HTML content of the RoosterJS editor programmatically? If setContent is not part of the package, how can I achieve similar functionality?
I’m not familiar with this library, so I might be saying something wrong. But it’s interesting that the code example from the library itself doesn’t work:
https://www.npmjs.com/package/roosterjs#usage
var contentDiv = document.getElementById('contentDiv');
var editor = roosterjs.createEditor(contentDiv);
editor.setContent('Welcome to <b>RoosterJs</b>!'); // Error: setContent is not defined
Through trial and error, from what I understand, we need to add an adapter:
https://www.npmjs.com/package/roosterjs-editor-adapter
I was able to make this setContent
available, but I don’t know why there are two different libraries, so in my code, I kept two variables.
I used npm
, but the documentation suggests yarn
npm install "roosterjs"
npm install "roosterjs-editor-adapter"
You can do this by importing it into your project like this:
import * as roosterjs from "roosterjs"
import { EditorAdapter } from "roosterjs-editor-adapter"
/*
OR via cdn:
import * as roosterjs from "https://cdn.jsdelivr.net/npm/[email protected]/+esm"
import { EditorAdapter } from "https://cdn.jsdelivr.net/npm/[email protected]/+esm"
*/
console.log("roosterjs", roosterjs)
console.log("EditorAdapter", EditorAdapter)
const contentDiv = document.getElementById("contentDiv"),
editor = roosterjs.createEditor(contentDiv), // Editor2 {core: {…}, cloneOptionCallback: ƒ}
editor2 = new EditorAdapter(contentDiv) // EditorAdapter2 {core: {…}, contentModelEditorCore: {…}, cloneOptionCallback: ƒ}
editor2.setContent("<strong>html code example</strong>")
That worked, the code was inserted into the <textarea>
. However, I’m not sure if there are any side effects from using editor
and editor2
.
I found some links that might add more information:
setContent
EditorAdapter