使用“pastefromword”过滤CKEditor 3中的所有粘贴内容

时间:2011-03-08 00:56:25

标签: javascript ckeditor paste

CKEditor是一个很棒的编辑器,pastefromword插件非常好。我想将插件提供的过滤应用于所有粘贴的文本。例如,从单词粘贴时,将删除所有字体和大小。从电子邮件粘贴时不会发生这种情况。

那就是说,我想出了以下解决方案并将其发布在这里以获得一些反馈。我想知道我是否过于复杂,或者是否有更简单的方法。我只是从pastefromword / plugin.js中复制了代码。

通过我的自定义config.js

...
CKEDITOR.config.pasteFromWordCleanupFile = '/pastefromword.js';
...
CKEDITOR.on( 'instanceReady', function( ev ) {
    /**
     * Paste event to apply Paste From Word filtering on all text.
     *
     * The pastefromword plugin will only process text that has tell-tale signs
     * it is from Word. Use this hook to treat all pasted text as if
     * it is coming from Word.
     *
     * This method is a slightly modified version of code found in
     * plugins/pastefromword/plugin.js
     */
    ev.editor.on( 'paste', function( evt ) {    
        var data = evt.data,
            editor = evt.editor,
            content;

        /**
         * "pasteFromWordHappened" is a custom property set in custom
         * pastefromword.js, so that filtering does not happen twice for content
         * actually coming from Word. It's a dirty hack I know.
         */
        if( editor.pasteFromWordHappened ) {
            // Reset property and exit paste event
            editor.pasteFromWordHappened = 0;
            return;
        }

        var loadRules = function( callback ) {
            var isLoaded = CKEDITOR.cleanWord;

            if( isLoaded ) {
                callback();
            }
            else {
                CKEDITOR.scriptLoader.load( CKEDITOR.config.pasteFromWordCleanupFile, callback, null, false, true );
            }

            return !isLoaded;
        };

        content = data['html'];

        // No need to filter text if html tags are not presence, so perform a regex
        // to test for html tags.
        if( content && (/<[^<]+?>/).test(content) ) {
            var isLazyLoad = loadRules( function(){
                if( isLazyLoad ) {
                    editor.fire('paste', data);
                }
                else {
                    data[ 'html' ] = CKEDITOR.cleanWord( content, editor );
                    // Reset property or if user tries to paste again, it won't work
                    editor.pasteFromWordHappened = 0;
                }
            });

            isLazyLoad && evt.cancel();
        }

    });
});

2 个答案:

答案 0 :(得分:11)

我的解决方案现在位于此博客条目中:http://www.keyvan.net/2012/11/clean-up-html-on-paste-in-ckeditor/

答案 1 :(得分:2)

评论一个老问题: 手头的问题不仅仅是CKEditor中的单词清理。 当你通过javascript api请求剪贴板内容时,它也是浏览器的功能。在IE,FF,Safari等之间存在很大差异。通常,非IE浏览器会自行清理HTML,而不是将HTML提供给浏览器。因此删除了大量格式。