This is a contenteditable element that you can create posts on facebook.com
All I want is inserting text into that contenteditable while keeping the new lines.
document.execCommand("insertText", false,"a sentence with \n\r a new line")
is not working, it just stripes \n
and \r
as we saw in the screenshot:
I have tried insertHTML, insertParagraph
commands but no luck.
I have seen that they append a <br/>
element when I press "Enter", so I also tried to append a <br/>
element but it doesn't work
Changing .value, .textContent, innerHTML, innerText
is not working as well.
I can't provide a MRE as it's a protected route.
Insert it in lines and manually dispatch the ShiftEnter key in-between:
function insertText(text, elem = document.querySelector('[contenteditable=true]')) {
elem.focus();
for (let i = 0, lines = text.split(/\r?\n/); i < lines.length; i++) {
// send a dummy keyCode:0 first to initialize the editor's React state.
elem.dispatchEvent(new KeyboardEvent('keydown', {keyCode: i && 13, shiftKey: true}));
document.execCommand('insertText', false, lines[i]);
}
}
Then call it as insertText('foo\nbar')