Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TinyMCE returning cursor to pre-save location -- API 4

I'm working on a new install of TinyMCE 4. The editor is a simple inline DIV, allowing only italic and bold (cleanup is set to remove most other tags).

tinymce.init({
    inline: true,

    // we only want simple bold and italic controls
    toolbar: "undo redo | bold italic", 

    invalid_elements : "span,u,a,ul,ol,li,h1,h2,h3,h4,h5,h6,blockquote,strikethrough",
    ...

My problem: I'd like to save the content of my editor back to my database via ajax every few keystrokes.

In order to run the cleanup, I first save the contents:

tinyMCE.triggerSave();  

then get the cleaned-up contents to send back to my database -- which, of course, traps appropriately for code-bombs, etc :)

var strData = tinymce.activeEditor.getContent() ;

This all works fine except that, back in the editor, the cursor get returned to the beginning of the content.

I thought I could return to the correct place by setting a bookmark before saving:

// set bookmark
var bm = tinymce.activeEditor.selection.getBookmark();

// save and cleanup, then ajax
tinyMCE.triggerSave(); 
...ajax stuff here

// Restore the selection bookmark
tinymce.activeEditor.selection.moveToBookmark(bm);

but this doesn't seem to work.

I also thought I could, perhaps, capture the current node and offset before saving:

var nd = tinymce.activeEditor.selection.getNode();
var os = tinymce.activeEditor.selection.getRng().startOffset;

and return to the correct point by:

tinymce.activeEditor.setCursorLocation(nd, os);

but this creates an error, as nd is apparently not a valid node object.

Is this because my 'selection' is actually a zero-length string (it's a cursor point, rather than a selection)?

I'm afraid that I'm having a few difficulties with the official documentation for API 4, which isn't as 'fleshed out' as the documentation for API 3 (I guess because it's a recent update).

Most of the help and examples that I can find on Stackoverflow (and general googling) relate to API 3 (which it seems is quite a different beast).

Can anyone advise me if what I want is possible?

like image 539
JonJ Avatar asked Mar 23 '23 19:03

JonJ


1 Answers

Hmm, you could use a non-html bookmark:

// set bookmark
var bm = tinymce.activeEditor.selection.getBookmark(2,true);

// save and cleanup, then ajax
tinyMCE.triggerSave(); 
...ajax stuff here

// Restore the selection bookmark
tinymce.activeEditor.selection.moveToBookmark(bm);
like image 127
Thariama Avatar answered Mar 26 '23 10:03

Thariama