Cómo hacer que tinymce pegue en texto sin formato por defecto


Lo googleó miles de veces, Nadie da una solución completa de cómo hacer que Tinymce pegue en texto plano por defecto y elimine cualquier formato sin hacer clic en el botón "pegar como texto".

¿Alguna idea de cómo implementar eso? ¿o cómo habilitar el botón" pegar como texto " automáticamente?

Gracias

Author: Ryan, 2010-04-23

10 answers

EDIT: esta solución es para la versión 3.x, para 4.versión x lea la respuesta de @ Paulo Neves

El problema es que el complemento Pegar restablece automáticamente el pegado de texto plano en cada pegado. Así que todo lo que tenemos que hacer es retrasarlo. El siguiente código debería ayudar.

tinyMCE.init({
...
oninit : "setPlainText",
plugins : "paste"

....
});

La definición de setPlainText

 function setPlainText() {
        var ed = tinyMCE.get('elm1');

        ed.pasteAsPlainText = true;  

        //adding handlers crossbrowser
        if (tinymce.isOpera || /Firefox\/2/.test(navigator.userAgent)) {
            ed.onKeyDown.add(function (ed, e) {
                if (((tinymce.isMac ? e.metaKey : e.ctrlKey) && e.keyCode == 86) || (e.shiftKey && e.keyCode == 45))
                    ed.pasteAsPlainText = true;
            });
        } else {            
            ed.onPaste.addToTop(function (ed, e) {
                ed.pasteAsPlainText = true;
            });
        }
    }

Así que ahora siempre será claro.

 48
Author: er-v,
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-10-14 08:36:47

Para el TinyMCE 3X o 4X las cosas han cambiado un poco. ahora puedes hacer esto y funciona bien.

tinymce.init({
    plugins: "paste",
    paste_as_text: true
});
 121
Author: Paulo Almeida,
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-05-05 11:09:19

He resuelto este problema con este código

tinyMCE.init({
...
plugins : "paste",
paste_text_sticky : true,
setup : function(ed) {
    ed.onInit.add(function(ed) {
      ed.pasteAsPlainText = true;
    });
  }
....
})
 80
Author: Dariusz Lyson,
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
2010-08-27 08:56:55

Acabo de encontrarme con este y descubrí que a partir de TinyMCE 3.4.2 puedes simplemente:

paste_text_sticky: true,
paste_text_sticky_default: true

...lo cual estuvo bien.

 35
Author: stovroz,
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
2012-01-06 00:42:15

Creo que la forma más fácil sería esta:

tinymce.init({
   ...
   paste_as_text: true,
   plugins: "paste",
   ...
});
 4
Author: brothers28,
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-01-19 09:58:52

, ¿no es mejor usar:

var ed = tinyMCE.activeEditor;

En lugar de:

var ed = tinyMCE.get('elm1');
 1
Author: Asen Mitov,
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
2011-05-27 09:48:46

PARA tu información, TinyMCE ha mejorado esto implementándolo como una opción predeterminada en el complemento pegar. Más información: http://www.tinymce.com/wiki.php/Plugin:paste

Sin embargo, todavía no es perfecto. Así que aquí hay un script que también se sale de todo HTML:

// Paste
        paste_auto_cleanup_on_paste : true,
        paste_remove_spans: true,
        paste_remove_styles: true,
        paste_retain_style_properties: false,

        paste_preprocess : function(pl, o) 
        {    // Replace <div> with <p>
            o.content = o.content.replace(/<div>/gi, "<p>");    
            o.content = o.content.replace(/<\/div>/gi, "</p>");
            o.content = o.content.replace(/<\r\n/gi, "\n");
            o.content = o.content.replace(/<\n\n/gi, "\n");
            o.content = o.content.replace(/<\n\n/gi, "\n");

            // Replace empty styles
            o.content = o.content.replace(/<style><\/style>/gi, "");    

            o.wordContent = true;            
        },

        paste_postprocess : function(pl, o) 
        {    //console.log(o.node.innerHTML);
            var ed = pl.editor, dom = ed.dom;

            // Remove all tags which are not <p> or <br>
            tinymce.each(dom.select('*', o.node), function(el) 
            {    if (el.tagName.toLowerCase() != "p" && el.tagName.toLowerCase() != "br") 
                {    dom.remove(el, 1); // 1 = KeepChildren
                    console.log(el.tagName);
                }
                dom.setAttrib(el, 'style', '');
            });

        },

Fuente: http://www.tinymce.com/forum/viewtopic.php?pid=60121#p60121

 1
Author: laarsk,
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
2012-03-08 09:48:28

Sin plug-in: Escuchar pegar evento, obtener datos del portapapeles

Si no puede usar o no desea usar un complemento por cualquier razón, puede crear su propia función de devolución de llamada" pegar como texto sin formato " de la siguiente manera:

tinyMCE.init({

    // ...,

    setup: function (editor) {

        // Listen for paste event, add "Paste as plain text" callback
        editor.onPaste.add(function (editor, e) {

            // Prevent default paste behavior
            e.preventDefault();

            // Check for clipboard data in various places for cross-browser compatibility.
            // Get that data as text.
            var content = ((e.originalEvent || e).clipboardData || window.clipboardData).getData('Text');

            // Let TinyMCE do the heavy lifting for inserting that content into the editor.
            editor.execCommand('mceInsertContent', false, content);
        });
    }
});

Nota: Esto fue creado para TinyMCE 3.5.x. La compatibilidad puede variar según la versión.

 1
Author: gfullam,
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-02-02 21:21:32

Hice lo siguiente:

var pastePlainText = function() {
    // No need to pass in an ID, instead fetch the first tinyMCE instance
    var ed = tinyMCE.get(0); 
    ed.pasteAsPlainText = true;  

    //adding handlers crossbrowser
    if (tinymce.isOpera || /Firefox\/2/.test(navigator.userAgent)) {
        ed.onKeyDown.add(function (ed, e) {
            if (((tinymce.isMac ? e.metaKey : e.ctrlKey) && e.keyCode == 86) || (e.shiftKey && e.keyCode == 45))
                ed.pasteAsPlainText = true;
        });
    } else {            
        ed.onPaste.addToTop(function (ed, e) {
            ed.pasteAsPlainText = true;
        });
    }
};

Y luego:

tinyMCE.init({
    // ...
    plugins: "paste",
    oninit: pastePlainText // Note, without "
    // ...
})
 0
Author: Helge,
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
2012-07-17 10:53:17

No estoy seguro de que esto sea posible, ya que "pegar como texto plano" en realidad realiza una limpieza en el texto antes de que lo agregue a la ventana. Si solo pega datos en la ventana, no se pueden realizar operaciones. (A menos que se enganchó en el onChange o algo), pero que podría terminar fijando el código que ya había sido pegado y por lo tanto, 'doble fijación'.

 -1
Author: Mitch Dempsey,
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
2010-04-29 03:12:32