How does execCommand "insertBrOnReturn" work?

9k views Asked by At

I tried the following code on Chrome:

document.execCommand("insertBrOnReturn", false, true);

http://jsfiddle.net/uVcd5/

Wether I set the last parameter to true or false, the behaviour doesn't change: on return, new <div> elements will be added.

Must have missed something... any ideas?

3

There are 3 answers

2
Andrew On BEST ANSWER

insertBrOnReturn is a Mozilla specific command, Chrome doesn't support it. You can test that with:

 document.queryCommandSupported('insertBrOnReturn')

jsFiddle here, it alert true in Firefox, but false in Chrome.

If you want to insert <br> only, try:

document.execCommand('insertHTML', false, '<br><br>');

Also, check this: Prevent contenteditable adding <div> on ENTER - Chrome

2
christopherdan On

I came across this answer but didn't like how in Chrome if your cursor is at the beginning of a paragraph it adds two breaks. Changing the second <br> to \u200C makes Chrome work perfectly, not so much for Safari.

document.execCommand("insertHTML", false, "<br>\u200C");

What is \u200c? Not sure. Found it referenced here.

Dealing with line Breaks on contentEditable DIV

2
user2280102 On
document.execCommand("insertLineBreak");

According to: https://www.w3schools.com/jsref/met_document_execcommand.asp

You can check the specs command at: https://w3c.github.io/editing/docs/execCommand/#dfn-the-insertlinebreak-command