Search code examples
javascriptnext.jstinymce

Get current cursor position from TinyMCE


I have tried to get the current cursor position inside TinyMCE, but to no avail.

What I want is to create a change control, obtaining at what point the entire "textarea" begins to be written within TinyMCE to later save the text I entered to a database so that another person can review the text change and accept it. Or not.

I already tried with selectionStart, but it doesn't return anything, also with bookmark but it's only temporary and with selection.getSelect() it only gives me the position of the line I click, let's say I have 3 jumps of line all with 10 characters but if I click in the middle of line 2 instead of giving me the number 15 it returns me the 5 and also in line 1 and 3.

Is there a way to get the position of the pointer?


Solution

  • Have a look at this example of setting and getting the cursor position using TinyMCE's Bookmark Manager API:

    http://fiddle.tiny.cloud/yoiaab/1

    let tinyBookmark;
    function setCursor() {
        tinyBookmark = tinyMCE.activeEditor.selection.getBookmark(2);
    }
    
    function getCursor() {
        console.log(tinyBookmark);
        tinyMCE.activeEditor.focus()
        tinyMCE.activeEditor.selection.moveToBookmark(tinyBookmark); 
    }
    

    The tinyBookmark object can be stored in your db (console logged in the getCursor function).

    Docs: https://www.tiny.cloud/docs/tinymce/6/apis/tinymce.dom.bookmarkmanager/#BookmarkManager