Documentation: How to serialize / unserialize content to ProseMirror instance

Here is how I got @kzap’s approach to work for 0.17. I haven’t managed (yet) to find a solution for 0.20.

to initialize with HTML string

import {EditorState} from "prosemirror-state"
import {MenuBarEditorView} from "prosemirror-menu"
import {Schema, DOMParser, DOMSerializer} from "prosemirror-model"
import {addListNodes} from "prosemirror-schema-list"
import {exampleSetup} from "prosemirror-example-setup"
import {schema as baseSchema} from "prosemirror-schema-basic"

let schema = new Schema({
	nodes: addListNodes(baseSchema.nodeSpec, "paragraph block*", "block"),
	marks: baseSchema.markSpec
});
let parser = (content) => {
    let domNode = document.createElement("div");
    domNode.innerHTML = content;
    return DOMParser.fromSchema(schema).parse(domNode);
}
let pm = new MenuBarEditorView(place, {
  	state: EditorState.create({
  	    doc: parser(place),
        plugins: exampleSetup({schema: schema})
  	}),
  	onAction: function(action) {
        pm.updateState(pm.editor.state.applyAction(action))
  	}
})

to get HTML string

let getContentString = () => {
    let fragment = DOMSerializer.fromSchema(schema).serializeFragment(pm.editor.state.doc.content);
    let tmp = document.createElement("div");
    tmp.appendChild(fragment);
    return tmp.innerHTML;
};
2 Likes