Search code examples
angulartypescriptckeditor

Get caret position in a CKEditor


I have a CKEditor in my template (unfortunately it is not my decision to use something else over this) of which I need to insert a pre-determined string into the existing text in the body at the current caret position. I cannot find a good way to obtain the position and any other support for this issue is scarce.

Does anyone know a way this this is possible?

Component

template = new Template() // eventually gets set
@ViewChild("cke-editor-name") editor: ElementRef;
insertText(string) {
    var caretPos = ???;
    template.BodyHtml = template.BodyHtml.substr(0, caretPos) + string + template.BodyHtml.substr(caretPos, string.length());
}

Solution

  • Finally found a way that works well for me on every browser.

    getCaretPos(){
        let sel = window.getSelection();
        let range;
        if (typeof document.caretPositionFromPoint !== "undefined") {
          var e = sel
            .getRangeAt(0)
            .cloneRange()
            .getBoundingClientRect()[0];
          range = document.caretPositionFromPoint(e.clientX, e.clientY);
        } else if (sel && sel.rangeCount > 0) {
          range = sel.getRangeAt(0);
        }
        if (!range) return;
        var caretPos = range.startOffset;
        return caretPos;
    }