This code is the best I could get , but it doesn't work for Twitter site:
function GetDivCaretPosition(target) {
if (target.isContentEditable || document.designMode === "on") {
target.focus();
const _range = document.getSelection().getRangeAt(0);
if (!_range.collapsed) {
return null;
}
const range =
_range.cloneRange();
const temp =
document.createTextNode("\0");
range.insertNode(temp);
const caretposition = target.innerText.indexOf("\0");
temp.parentNode.removeChild(temp);
return caretposition;
}
} `
(For my chrome extension -)
I want to know if the user is adding the character to the end of the text, or, inserting it within (before the end of) the text.
This question was asked three years ago , so I hope I can raise it again. (asked by @rugk)
The problem with Twitter is that by creating/removing textNode , the cursor retreats back and the text is gotten confused.
I think of some workaround :
When the resulted text is appearing - to check if there was a change in the last line(more accurate, the last unique substring in the last line).
If there was no change , this says that the letter was added before the end of the text.
Then , we need to repeat again and display the text on the basis of this situation.
But I would be glad to know a good function to get the caret position in all the sites , including Twitter.