在execCommand中'粘贴为纯文本'的Javascript技巧

时间:2012-08-19 14:10:34

标签: javascript html5 javascript-events execcommand

我有一个基于execCommand的基本编辑器,遵循此处介绍的示例。在execCommand区域中粘贴文本有三种方法:

  • Ctrl + V
  • 右键单击 - >粘贴
  • 右键单击 - >粘贴为纯文本

我想只允许粘贴纯文本而不添加任何HTML标记。如何强制前两个操作粘贴纯文本?

可能的解决方案:我能想到的方法是为( Ctrl + V )设置keyup事件的监听器并删除HTML标签粘贴之前。

  1. 这是最好的解决方案吗?
  2. 是否可以防止粘贴中出现任何HTML标记?
  3. 如何将监听器添加到右键单击 - >粘贴?

11 个答案:

答案 0 :(得分:204)

它将拦截paste事件,取消paste,并手动插入剪贴板的文本表示:
http://jsfiddle.net/HBEzc/。 这应该是最可靠的:

  • 它捕获各种粘贴( Ctrl + V ,上下文菜单等)
  • 它允许您直接以文本形式获取剪贴板数据,因此您无需使用丑陋的黑客来替换HTML。

但我不确定跨浏览器支持。

editor.addEventListener("paste", function(e) {
    // cancel paste
    e.preventDefault();

    // get text representation of clipboard
    var text = (e.originalEvent || e).clipboardData.getData('text/plain');

    // insert text manually
    document.execCommand("insertHTML", false, text);
});

答案 1 :(得分:33)

我无法在IE中获得接受的答案,所以我做了一些侦察,并得出了这个答案,适用于IE11以及最新版本的Chrome和Firefox。

$('[contenteditable]').on('paste', function(e) {
    e.preventDefault();
    var text = '';
    if (e.clipboardData || e.originalEvent.clipboardData) {
      text = (e.originalEvent || e).clipboardData.getData('text/plain');
    } else if (window.clipboardData) {
      text = window.clipboardData.getData('Text');
    }
    if (document.queryCommandSupported('insertText')) {
      document.execCommand('insertText', false, text);
    } else {
      document.execCommand('paste', false, text);
    }
});

答案 2 :(得分:19)

作为pimvdb的密切解决方案。但它适用于FF,Chrome和IE 9:

editor.addEventListener("paste", function(e) {
    e.preventDefault();

    if (e.clipboardData) {
        content = (e.originalEvent || e).clipboardData.getData('text/plain');

        document.execCommand('insertText', false, content);
    }
    else if (window.clipboardData) {
        content = window.clipboardData.getData('Text');

        document.selection.createRange().pasteHTML(content);
    }   
});

答案 3 :(得分:17)

当然问题已经回答了,主题已经很老了,但我想提供我的解决方案,因为它简单干净:

这是在我的contenteditable-div上的粘贴事件中。

var text = '';
var that = $(this);

if (e.clipboardData)
    text = e.clipboardData.getData('text/plain');
else if (window.clipboardData)
    text = window.clipboardData.getData('Text');
else if (e.originalEvent.clipboardData)
    text = $('<div></div>').text(e.originalEvent.clipboardData.getData('text'));

if (document.queryCommandSupported('insertText')) {
    document.execCommand('insertHTML', false, $(text).html());
    return false;
}
else { // IE > 7
    that.find('*').each(function () {
         $(this).addClass('within');
    });

    setTimeout(function () {
          // nochmal alle durchlaufen
          that.find('*').each(function () {
               // wenn das element keine klasse 'within' hat, dann unwrap
               // http://api.jquery.com/unwrap/
               $(this).not('.within').contents().unwrap();
          });
    }, 1);
}

其他部分来自另一个我找不到的SO帖子......


更新19.11.2014: The other SO-post

答案 4 :(得分:3)

Firefox不允许您访问剪贴板数据,因此您需要进行“黑客攻击”才能使其正常工作。我无法找到完整的解决方案,但你可以通过创建textarea&amp; amp来修复ctrl + v pastes。反而粘贴:

//Test if browser has the clipboard object
if (!window.Clipboard)
{
    /*Create a text area element to hold your pasted text
    Textarea is a good choice as it will make anything added to it in to plain text*/           
    var paster = document.createElement("textarea");
    //Hide the textarea
    paster.style.display = "none";              
    document.body.appendChild(paster);
    //Add a new keydown event tou your editor
    editor.addEventListener("keydown", function(e){

        function handlePaste()
        {
            //Get the text from the textarea
            var pastedText = paster.value;
            //Move the cursor back to the editor
            editor.focus();
            //Check that there is a value. FF throws an error for insertHTML with an empty string
            if (pastedText !== "") document.execCommand("insertHTML", false, pastedText);
            //Reset the textarea
            paster.value = "";
        }

        if (e.which === 86 && e.ctrlKey)
        {
            //ctrl+v => paste
            //Set the focus on your textarea
            paster.focus();
            //We need to wait a bit, otherwise FF will still try to paste in the editor => settimeout
            window.setTimeout(handlePaste, 1);
        }

    }, false);
}
else //Pretty much the answer given by pimvdb above
{
    //Add listener for paster to force paste-as-plain-text
    editor.addEventListener("paste", function(e){

        //Get the plain text from the clipboard
        var plain = (!!e.clipboardData)? e.clipboardData.getData("text/plain") : window.clipboardData.getData("Text");
            //Stop default paste action
        e.preventDefault();
        //Paste plain text
        document.execCommand("insertHTML", false, plain);

    }, false);
}

答案 5 :(得分:3)

所有发布的答案都没有真正跨浏览器工作或解决方案过于复杂:

  • IE
  • 不支持命令insertText
  • 使用paste命令导致IE11中的堆栈溢出错误

对我有用的东西(IE11,Edge,Chrome和FF)如下:

&#13;
&#13;
$("div[contenteditable=true]").off('paste').on('paste', function(e) {
    e.preventDefault();
    var text = e.originalEvent.clipboardData ? e.originalEvent.clipboardData.getData('text/plain') : window.clipboardData.getData('Text');
    _insertText(text);
});

function _insertText(text) { 
    // use insertText command if supported
    if (document.queryCommandSupported('insertText')) {
        document.execCommand('insertText', false, text);
    }
    // or insert the text content at the caret's current position
    // replacing eventually selected content
    else {
        var range = document.getSelection().getRangeAt(0);
        range.deleteContents();
        var textNode = document.createTextNode(text);
        range.insertNode(textNode);
        range.selectNodeContents(textNode);
        range.collapse(false);

        var selection = window.getSelection();
        selection.removeAllRanges();
        selection.addRange(range);
    }
};
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<body>
<textarea name="t1"></textarea>
<div style="border: 1px solid;" contenteditable="true">Edit me!</div>
<input />
</body>
&#13;
&#13;
&#13;

请注意,自定义粘贴处理程序仅适用于contenteditable个节点。由于textarea和普通input字段都不支持粘贴HTML内容,因此无需在此处进行任何操作。

答案 6 :(得分:2)

我还在处理一个纯文本粘贴,我开始讨厌所有的execCommand和getData错误,所以我决定以经典的方式做它,它就像一个魅力:

$('#editor').bind('paste', function(){
    var before = document.getElementById('editor').innerHTML;
    setTimeout(function(){
        var after = document.getElementById('editor').innerHTML;
        var pos1 = -1;
        var pos2 = -1;
        for (var i=0; i<after.length; i++) {
            if (pos1 == -1 && before.substr(i, 1) != after.substr(i, 1)) pos1 = i;
            if (pos2 == -1 && before.substr(before.length-i-1, 1) != after.substr(after.length-i-1, 1)) pos2 = i;
        }
        var pasted = after.substr(pos1, after.length-pos2-pos1);
        var replace = pasted.replace(/<[^>]+>/g, '');
        var replaced = after.substr(0, pos1)+replace+after.substr(pos1+pasted.length);
        document.getElementById('editor').innerHTML = replaced;
    }, 100);
});

我的符号代码可以在这里找到: http://www.albertmartin.de/blog/code.php/20/plain-text-paste-with-javascript

答案 7 :(得分:1)

function PasteString() {
    var editor = document.getElementById("TemplateSubPage");
    editor.focus();
  //  editor.select();
    document.execCommand('Paste');
}

function CopyString() {
    var input = document.getElementById("TemplateSubPage");
    input.focus();
   // input.select();
    document.execCommand('Copy');
    if (document.selection || document.textSelection) {
        document.selection.empty();
    } else if (window.getSelection) {
        window.getSelection().removeAllRanges();
    }
}

以上代码适用于IE10和IE11,现在也适用于Chrome和Safari。未在Firefox中测试过。

答案 8 :(得分:1)

在IE11中,execCommand不能正常工作。我使用IE11下面的代码 <div class="wmd-input" id="wmd-input-md" contenteditable=true> 是我的div box。

我从window.clipboardData读取剪贴板数据并修改div的textContent并给予插入符号。

我为设置插入符号给出超时,因为如果我没有设置超时,则插入符号将结束div。

你应该以下面的方式阅读IE11中的clipboardData。如果你不这样做,换行符不能正确处理,因此插入错误。

var tempDiv = document.createElement("div");
tempDiv.textContent = window.clipboardData.getData("text");
var text = tempDiv.textContent;

在IE11和Chrome上测试过。它可能无法在IE9上运行

document.getElementById("wmd-input-md").addEventListener("paste", function (e) {
    if (!e.clipboardData) {
        //For IE11
        e.preventDefault();
        e.stopPropagation();
        var tempDiv = document.createElement("div");
        tempDiv.textContent = window.clipboardData.getData("text");
        var text = tempDiv.textContent;
        var selection = document.getSelection();
        var start = selection.anchorOffset > selection.focusOffset ? selection.focusOffset : selection.anchorOffset;
        var end = selection.anchorOffset > selection.focusOffset ? selection.anchorOffset : selection.focusOffset;                    
        selection.removeAllRanges();

        setTimeout(function () {    
            $(".wmd-input").text($(".wmd-input").text().substring(0, start)
              + text
              + $(".wmd-input").text().substring(end));
            var range = document.createRange();
            range.setStart(document.getElementsByClassName("wmd-input")[0].firstChild, start + text.length);
            range.setEnd(document.getElementsByClassName("wmd-input")[0].firstChild, start + text.length);

            selection.addRange(range);
        }, 1);
    } else {                
        //For Chrome
        e.preventDefault();
        var text = e.clipboardData.getData("text");

        var selection = document.getSelection();
        var start = selection.anchorOffset > selection.focusOffset ? selection.focusOffset : selection.anchorOffset;
        var end = selection.anchorOffset > selection.focusOffset ? selection.anchorOffset : selection.focusOffset;

        $(this).text($(this).text().substring(0, start)
          + text
          + $(this).text().substring(end));

        var range = document.createRange();
        range.setStart($(this)[0].firstChild, start + text.length);
        range.setEnd($(this)[0].firstChild, start + text.length);
        selection.removeAllRanges();
        selection.addRange(range);
    }
}, false);

答案 9 :(得分:0)

经过搜索和尝试,我找到了某种最佳解决方案

  

记住什么很重要

// /\x0D/g return key ASCII
window.document.execCommand('insertHTML', false, text.replace('/\x0D/g', "\\n"))


and give the css style white-space: pre-line //for displaying

var contenteditable = document.querySelector('[contenteditable]')
            contenteditable.addEventListener('paste', function(e){
                let text = ''
                contenteditable.classList.remove('empty')                
                e.preventDefault()
                text = (e.originalEvent || e).clipboardData.getData('text/plain')
                e.clipboardData.setData('text/plain', '')                 
                window.document.execCommand('insertHTML', false, text.replace('/\x0D/g', "\\n"))// /\x0D/g return ASCII
        })
#input{
  width: 100%;
  height: 100px;
  border: 1px solid black;
  white-space: pre-line; 
}
<div id="input"contenteditable="true">
        <p>
        </p>
</div>   

答案 10 :(得分:0)

好,因为每个人都在尝试处理剪贴板数据,检查按键事件并使用execCommand。

我想到了

CODE

<a className=""
   href="/project_path_to_your_pdf_asset/failename.pdf"
   target="_blank"
>
   View PDF
</a>
/mycmd @bob #my-channel

相关问题