I'm surprised I'm having trouble with this and unable to find an answer. I'm trying to get the text in a contenteditable, from the start of the contenteditable to the users cursor/caret.
Here's a jsFiddle of what I've attempted (click around the contenteditable and watch console.log).
I get the caret location and then I attempt to get the content:
I tried using textContent
of the contenteditable which works but if there's content like foo<br>bar
it outputs foobar
when ideally it should output foo\r\nbar
(Note: This is for a chrome extension I have no control over the content of the contenteditable).
innerText
works as expected outputting foo\r\nbar
, but as can be seen in the jsFiddle once the html in contenteditable gets a little complex the caret position doesn't seem to match the location in innerText
and I have trouble outputting up to the caret.
Found some code using the Range interface and modified it to meet my needs in this jsFiddle but had the same problem with <br>
as textContent
did.
Note: The user will continue typing as I get the content, so looking for something that doesn't break this flow.
Just looking for direction, any quick tips on what I should try?