Question

Does anyone know how I can attach an onpaste event in CKEditor 3.x?

I basically want to grab CTRL + V data and add few text to it and then add it to the editor.

I have looked around but have not found a definitive answer. CKEditor forum is of not much help.

Was it helpful?

Solution

This should do the trick

var editor = CKEDITOR.instances.YourInputControlName;
editor.on('paste', function(evt) {
    // Update the text
    evt.editor.setData(evt.editor.getData() + ' your additional comments.');
}, editor.element.$);

OTHER TIPS

Your both examples are a little bit synthetic.

At first, editor.getData() gets all the content of editor, so if you want to process only pasted data, you need to get ev.data.html and paste to correct place.

editor = CKEDITOR.instances.editor1;
editor.on('paste', function (evt) {
    var editor = evt.editor;
    evt.stop(); // we don't let editor to paste data, only for current event
    // show loader that blocks editor changes
    $.post('clean.php', {html: evt.data.html}, function (data) {
        editor.insertHtml( data.html ); // text will be inserted at correct place
        // hide loader
    }, 'json');
});

Don't use functions editor.setReadonly(true/false), you won't be able to paste text in correct place (in cases with async data processing).

This example edits the content to be pasted by removing all img elements.

CKEDITOR.on('instanceReady', function (ev) {
    ev.editor.on('paste', function (ev) {
        ev.data.html = ev.data.html.replace(/<img( [^>]*)?>/gi, '');
    });
});
editor = CKEDITOR.instances[id];

editor.on('paste', function (evt) {
    evt.stop();
    var data = evt.data.dataValue;

    if (window.chrome || window.safari) {
        // removing span wrapper on webkit browsers.
        data = $(data).html();
    }
    evt.editor.insertHtml(data);
});

I know it's an old question, but thought I'd add my version of aliaksej's answer as it allows the use of a custom 'cleaner' - it didn't quite work for me until I modded it as below.

editor = CKEDITOR.instances[id];
editor.on('paste', function (evt) { 
   evt.stop();
   $.post('/actions/clean.php', {html: evt.data.dataValue}).done(function (data) {
      evt.editor.insertHtml(data);
   }, 'json');
});
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top