Cómo detectar cambios en TinyMCE?


Agregué el editor TinyMCE(versión 4.0.2) en un formulario HTML existente en mi proyecto(PHP,Codeigniter). Mi objetivo final es habilitar el botón enviar formulario si se producen cambios en el formulario, incluido el editor TinyMCE. Solo puedo hacerlo con el formulario excepto TinyMCE editor. No pude detectar cambios en TinyMCE.

Quiero detectar si se produce algún cambio cuando se activa la tecla. He visto que tinymce tiene una función onchange como abajo.

            setup : function(ed) {
            ed.onChange.add(function(ed, l) {
                console.debug('Editor contents was modified. Contents: ' + l.content);
            });

Puse el código de configuración superior dentro del init de abajo función, pero no hay salida que he encontrado.

tinymce.init({ });

¿Puedes saber cómo detectar el cambio, o cualquier idea mejor?

Author: danronmoon, 2013-07-23

10 answers

Llego tarde a la fiesta, pero para referencia futura aquí es cómo lo haces en TinyMCE 4.X:

tinyMCE.init({
   setup:function(ed) {
       ed.on('change', function(e) {
           console.log('the event object ', e);
           console.log('the editor object ', ed);
           console.log('the content ', ed.getContent());
       });
   }
});
 53
Author: sica07,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-07-08 14:49:16

Para Tinymce 4 funciona para mí, {[15]]}

        editor.on('keyup', function(e) {
            alert('keyup occured');
            //console.log('init event', e);
            console.log('Editor contents was modified. Contents: ' + editor.getContent());
            check_submit(); //another function calling
        });

EDITAR:

Tenga en cuenta que keyup no capturará todos los casos. por ejemplo copy/paste/cut de menu y no de keyboard

Si quieres puedes capturarlos con {[15]]}

editor.on('paste', function(e) {
                    console.debug('paste event');

                });

editor.on('cut', function(e) {
                    console.debug('cut event');

                });

NOTA si captura cut y paste desde tinymce probablemente no debería procesar esos eventos desde keyup. Lo que hice es guardar solo si las llaves no son llaves para cut & paste i. e :

 /**
 * MCE keyup callback, update the master model selected attribute
 * 
 * @method tinyMCEKeyup
 */
 tinyMCEKeyUp : function(e) {
        console.log('tinymce:keyup');


         var ctrlDown = false;
         var ctrlKey = 17, vKey = 86, xKey = 88;


         if ((e.ctrlKey) && (e.keyCode === vKey)) {
             console.log('paste from keyboard')
             /* got here. do nothing. let paste event handle this one  */
             return;
         } else if ((e.ctrlKey) && (e.keyCode === xKey)) {
             console.log('cut from keyboard')
             /* got here. do nothing. let paste event handle this one  */
             return;
         }

         this.doSave();

},

Y llame a esto función del evento keyup. De esta manera te ahorrarás hacer algunas acciones dos veces en cut & paste

NOTA pronto descubrirás que cualquier style changes que suceda desde menu NO activará esos eventos también..

Todavía estoy buscando una respuesta para capturar el cambio de estilo.

 25
Author: user2603482,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-04-18 06:55:25

Eso funciona para mí:

tinyMCE.init({
    setup : function(ed){
         ed.on('NodeChange', function(e){
             console.log('the event object ' + e);
             console.log('the editor object ' + ed);
             console.log('the content ' + ed.getContent());
         });
    }
});

También

ed.on('SaveContent', function(e) {  

O

ed.on('submit', function(e) {

Encontrado en la página http://www.tinymce.com/wiki.php/api4:class.tinymce.Editor en la Sección Evento

 11
Author: Martin,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-01-27 20:24:26

Lo siguiente capturará "keyup" y otros eventos de cambio (copiar, pegar, centrar, etc.):

tinymce.init({
    setup: function (ed) {
        ed.on('keyup', function (e) {
            tinyMceChange(ed);
        });
        ed.on('change', function(e) {
            tinyMceChange(ed);
        });
    }
});

function tinyMceChange(ed) {
    console.debug('Editor contents was modified. Contents: ' + ed.getContent());
}
 8
Author: oalbrecht,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-04-20 13:08:01

Estoy usando esto en tinymce 4.x

tinymce.init({
    selector: "#tinymce-textarea",
    setup : function(ed) {
        ed.on("change", function(e){
            $('#tinymce-livepreview').html(tinymce.activeEditor.getContent());
        });
        ed.on("keyup", function(){
            $('#tinymce-livepreview').html(tinymce.activeEditor.getContent());
        });
   }
});

Explicación:

On("change") es para detectar cambios en el evento del mouse si hace clic en el icono de la barra de herramientas o en la selección del menú. También es capaz de detectar el evento del teclado, pero solo después de la pérdida de enfoque (no en tiempo real).

On ("keyup") es para detectar cambios en el evento de teclado en tiempo real

 6
Author: Syukri Hakim Abdul Rahman,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-08-28 02:37:47

Prueba esto:

tinyMCE.init({
   setup : function(ed) {
          ed.onChange.add(function(ed, l) {
                  var editorContent = l.content;    // editorContent will hold the values of the editor
                  alert(editorContent);
          });
   }
});

Haga clic para la referencia aquí

 3
Author: Nil'z,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-07-23 06:28:29

Hemos encontrado que el evento de cambio a veces solo se dispara después de presionar enter; Parece estar vinculado al proceso deshacer. Además, el evento keyup se dispara cuando el contenido no ha cambiado, como cuando se presiona shift o CMD-A.

Así que usamos changey keyup, y comparamos el último valor procesado con el valor actual para detectar un cambio real.

Esta solución también funciona para cortar, pegar y modificaciones de elementos del menú.

//Sometimes does not fire unless enter is pressed
editor.on('change', () => {
    var value = editor.getContent();
    if (value !== editor._lastChange) {
        editor._lastChange = value;
        window.console.log(editor._lastChange);
    }
});

//Sometimes fires even if content did not change
editor.on('keyup', () => {
    var value = editor.getContent();
    if (value !== editor._lastChange) {
        editor._lastChange = value;
        window.console.log(editor._lastChange);
    }
});
 1
Author: Steven Spungin,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-08-13 11:08:30

Esto funciona bien para mí en toda condtion key up, cut , copy, paste

    setup: function (editor) {
        editor.on('KeyUp', function(e){
            alert(editor.getContent());
         });
}
 1
Author: sandeep kumar,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-03-14 08:45:13
tinymce.init({
    // ...
    setup: function(editor) {
        editor.on('Paste Change input Undo Redo', function () {
            if (editorChangeHandler) {clearTimeout(editorChangeHandler);}
            editorChangeHandler = setTimeout(function() {
                console.log('changed');
            }, 100);
        });
    }
    // ,...
});
 1
Author: Nagy Zoltán,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-03-28 09:05:18

Hola he intentado usar esto:

setup : function(ed) {
    ed.onChange.add(function() {
        $('#changed').val(1);
    });
}

Esto es para actualizar un campo oculto "cambiado" con el valor de 1 para que cuando un usuario intente cerrar el panel o salir de la página se le informe de que tiene datos no guardados.

Mi culpa es que esto solo funciona si se realizan 2 o más cambios, por ejemplo, si noté que no había terminado con un punto "."volví a agregar esto, luego por alguna razón hice clic en cerrar sería capaz de salir de la página sin ser advertido de los cambios

 -1
Author: Gravesy,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-12-06 22:31:46