-
|
Does anyone know if it is possible to get the editor content as html and/or replace the content of a Lexical editor with my own HTML from a browser extension content script in Main World isolation, or anywhere for that matter? For context, I need to get, then modify a lexical editors html content and then reinsert it into the editor I'm aware that the editor data is in a JSON format, but I don't see any way to change that from the outside either, though the content I need to insert is in HTML, so i'd need to convert it to/from JSON in that case. Changing the contenteditable's HTML doesn't work, and I only seem to be able to modify text content with the "beforeinput" event, but I cannot change the structure. The following can be tested in devtools on the editor playground at https://playground.lexical.dev/ this is how close i've come. function insertHTMLIntoLexical(htmlString) {
const rootElement = document.querySelector('div[data-lexical-editor]');
if (!rootElement) {
throw new Error('Lexical editor not found');
}
const editor = rootElement.__lexicalEditor;
if (!editor) {
throw new Error('LexicalEditor instance not accessible');
}
const cmdRef= [...editor._commands.keys()].find(
cmd => cmd?.type === "PASTE_COMMAND"
);
if (!cmdRef) {
throw new Error("PASTE_COMMAND not found in editor._commands dict");
}
const data = new DataTransfer();
data.setData('text/html', htmlString);
data.setData('text/plain', htmlString.replace(/<[^>]*>/g, ''));
const pasteEvent = new ClipboardEvent('paste', {
clipboardData: data
});
editor.dispatchCommand(cmdRef, pasteEvent);
} |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments
-
|
Pasting should work fine, I would dispatch it natively through DOM rather than using implementation details. Your problem may be that there isn't a selection in that element |
Beta Was this translation helpful? Give feedback.
-
|
Thanks for the help. function dispatchSyntheticPaste(target: HTMLElement, html: string) {
const text = htmlToPlainText(html); //you get the idea
const data = new DataTransfer();
data.setData("text/html", html);
data.setData("text/plain", text);
const evt = new Event("paste", {
bubbles: true,
cancelable: true,
composed: true,
}) as ClipboardEvent;
Object.defineProperty(evt, "clipboardData", {
value: data,
});
target.dispatchEvent(evt);
}
export function replaceContentEditableHTML(root: HTMLElement, html: string) {
root.focus();
document.execCommand("selectAll");
document.execCommand("delete");
dispatchSyntheticPaste(root, html);
}Unfortunately, selectAll followed by the dispatch event still just appends the new html instead of replacing it, hence the 'delete' first. |
Beta Was this translation helpful? Give feedback.
Pasting should work fine, I would dispatch it natively through DOM rather than using implementation details. Your problem may be that there isn't a selection in that element