商城首页欢迎来到中国正版软件门户

您的位置: 首页 > 文章列表 > 编程开发 > Html 编辑器粘贴内容过滤技术详解

Html 编辑器粘贴内容过滤技术详解

  发布于2026-07-22 阅读(0)

扫一扫,手机访问

最近在解决数据粘贴方面取得了不少进展,这是HTML在线编辑器所必须具备的技术。这里详细给大家介绍整个过程,并提供实现参考。研究过程中确实走了不少弯路,尝试了多种方式——由于美国的PM始终觉得有些影响用户体验的东西无法接受,导致好几个提案被否掉,不过收获还是相当丰富的。

现在写代码喜欢需求驱动,先来看看这项技术的主要需求:

  • 能够过滤用户贴进来的纯文本数据
  • 能够过滤用户贴进来的HTML数据(未经HTML编码)
  • 能够过滤用户贴进来的Word数据,并能把大部分Word格式保留下来
  • 在这一过程中尽量不要让用户知道我们在做过滤
  • 不要去提示用户是否启用某种权限

本例所适用的场景为使用iframe实现的HTML编辑器,而不是文本框(textarea或type为text的input)。

研究过程中,主要参考了TinyMCE和CKEditor,但最后选择了TinyMCE的实现方法,具体原因在看完下面这段文字后就会明白。

CKEditor的实现方式是在onpaste事件触发时,从剪贴板取出数据,处理取出的文本,然后再把处理好的文本存入剪贴板。有人可能会问:能不能在onpaste中直接取消paste动作,然后自己把获得的内容放入iframe当中?当时也试过这条路,但结果出人意料——直接从剪贴板拿出的数据是不包括格式信息的文本,特别是从Word粘贴过来的数据,纯文本,颜色、布局等数据都不存在。这样一来,用户只能粘贴没有格式的数据过来,然后自己重新在HTML编辑器里面编辑。但如果让浏览器自己去做粘贴,格式信息都会保留,浏览器会自动把Word的粘贴数据转换为XML数据,放入DOM中。所以为了保留格式信息,恐怕只能通过浏览器的标准粘贴行为的帮助来实现这一点。

另外,CKEditor在Firefox中有一个致命的弱点:如果你要从剪贴板读写数据,就必须提示用户自己去设置一个叫signed.applets.codebase_principal_support的权限,Ja vaScript脚本是没有权限去设置的。虽然从技术角度来看这是很正常的,但很多产品经理无法接受这一点——至少我遇到的PM是这么认为的。

以下是CKEditor获取和设置剪贴板的代码,供参考。

复制代码

function setClipboard(maintext) {
    if (window.clipboardData) {
        return (window.clipboardData.setData("Text", maintext));
    }
    else if (window.netscape) {
        netscape.security.PrivilegeManager.enablePrivilege('UniversalXPConnect');
        var clip = Components.classes['@mozilla.org/widget/clipboard;1'].createInstance(Components.interfaces.nsIClipboard);
        if (!clip) return;
        var trans = Components.classes['@mozilla.org/widget/transferable;1'].createInstance(Components.interfaces.nsITransferable);
        if (!trans) return;
        trans.addDataFla vor('text/unicode');
        var str = new Object();
        var len = new Object();
        var str = Components.classes["@mozilla.org/supports-string;1"].createInstance(Components.interfaces.nsISupportsString);
        var copytext=maintext;
        str.data=copytext;
        trans.setTransferData("text/unicode",str,copytext.length*2);
        var clipid=Components.interfaces.nsIClipboard;
        if (!clip) return false;
        clip.setData(trans,null,clipid.kGlobalClipboard);
        return true;
    }
    return false;
}
function getClipboard() {
    if (window.clipboardData) {
        return(window.clipboardData.getData('Text'));
    }
    else if (window.netscape) {
        netscape.security.PrivilegeManager.enablePrivilege('UniversalXPConnect');
        var clip = Components.classes['@mozilla.org/widget/clipboard;1'].createInstance(Components.interfaces.nsIClipboard);
        if (!clip) return;
        var trans = Components.classes['@mozilla.org/widget/transferable;1'].createInstance(Components.interfaces.nsITransferable);
        if (!trans) return;
        trans.addDataFla vor('text/unicode');
        clip.getData(trans,clip.kGlobalClipboard);
        var str = new Object();
        var len = new Object();
        try {
            trans.getTransferData('text/unicode',str,len);
        }
        catch(error) {
            return null;
        }
        if (str) {
            if (Components.interfaces.nsISupportsWString) str=str.value.QueryInterface(Components.interfaces.nsISupportsWString);
            else if (Components.interfaces.nsISupportsString) str=str.value.QueryInterface(Components.interfaces.nsISupportsString);
            else str = null;
        }
        if (str) {
            return(str.data.substring(0,len.value / 2));
        }
    }
    return null;
}

以下是提示用户启用权限的代码:

复制代码

if (window.netscape)
{
    try
    {
        netscape.security.PrivilegeManager.enablePrivilege("UniversalXPConnect");
    }
    catch (ex)
    {
        alert("If you want to do paste, please input 'about:config' in address bar, then input Enter.\n Set \"signed.applets.codebase_principal_support\" to \"true\"");
    }
}

于是转向了TinyMCE的实现方式。在看它的代码时,特别留意到它竟然不需要权限就能在Firefox下面搞定粘贴,并且还能保留Word格式,于是仔细阅读了其中的逻辑。TinyMCE的实现步骤在IE和Firefox下面是不同的:

IE实现

  1. 在onpaste回调函数中创建一个临时的iframe,用于粘贴内容,这个iframe放在主窗口的body下面即可。
  2. 在当前光标位置创建一个Range,用来保存光标位置和选中信息。
  3. 让临时iframe获得焦点,执行粘贴命令,即document.execCommand(“paste”),内容会粘贴在临时的iframe中。
  4. 通过innerHTML获得临时iframe中的内容并进行过滤。
  5. 让HTML编辑器的iframe获得焦点,用之前创建的Range对象执行pasteHTML方法来粘贴过滤后的内容。
  6. 最后取消默认的paste动作。

(临时iframe可以根据个人喜好从DOM中删除,但由于这个iframe可以在多个HTML编辑器之间共用,所以实现中仅仅改变了iframe的left、top来调整iframe的位置,而不是移除它。调整left和top的目的在于:焦点移到临时iframe的时候,如果HTML编辑器的iframe和临时iframe不在一个视图之内,屏幕会滚动,这样会导致屏幕没有原因的闪烁。)

Firefox实现

  1. 在onpaste回调函数中创建一个临时的div,这个div放在HTML编辑器的iframe里面——这也是绕过权限问题的关键。
  2. 保存当前光标和焦点位置,然后将光标移到临时创建的div中。
  3. 通过window.setTimeout设置一个回调函数,在paste动作瞬间完成之后执行。
  4. 让paste动作执行(onpaste回调函数执行完毕)。
  5. 刚才设置的回调函数执行,在里面获得临时div的innerHTML并进行过滤。
  6. 恢复刚才保存的光标和焦点位置,并移除临时div。
  7. 通过inserthtml命令(execCommand(“inserthtml”))把过滤后的内容贴到HTML编辑器的iframe中。

详细代码如下:

复制代码

function getSel(w)
{
    return w.getSelection ? w.getSelection() : w.document.selection;
}
function setRange(sel,r)
{
    sel.removeAllRanges();
    sel.addRange(r);
}
function filterPasteData(originalText)
{
    var newText=originalText;
    //do something to filter unnecessary data
    return newText;
}
function block(e)
{
    e.preventDefault();
}
var w,or,divTemp,originText;
var newData;
function pasteClipboardData(editorId,e)
{
    var objEditor = document.getElementById(editorId);
    var edDoc=objEditor.contentWindow.document;
    if(isIE)
    {
        var orRange=objEditor.contentWindow.document.selection.createRange();
        var ifmTemp=document.getElementById("ifmTemp");
        if(!ifmTemp)
        {
            ifmTemp=document.createElement("IFRAME");
            ifmTemp.id="ifmTemp";
            ifmTemp.style.width="1px";
            ifmTemp.style.height="1px";
            ifmTemp.style.position="absolute";
            ifmTemp.style.border="none";
            ifmTemp.style.left="-10000px";
            ifmTemp.src="iframeblankpage.html";
            document.body.appendChild(ifmTemp);
            ifmTemp.contentWindow.document.designMode = "On";
            ifmTemp.contentWindow.document.open();
            ifmTemp.contentWindow.document.write("");
            ifmTemp.contentWindow.document.close();
        }else
        {
            ifmTemp.contentWindow.document.body.innerHTML="";
        }
        originText=objEditor.contentWindow.document.body.innerText;
        ifmTemp.contentWindow.focus();
        ifmTemp.contentWindow.document.execCommand("Paste",false,null);
        objEditor.contentWindow.focus();
        newData=ifmTemp.contentWindow.document.body.innerHTML;
        //filter the pasted data
        newData=filterPasteData(newData);
        ifmTemp.contentWindow.document.body.innerHTML=newData;
        //paste the data into the editor
        orRange.pasteHTML(newData);
        //block default paste
        if(e)
        {
            e.returnValue = false;
            if(e.preventDefault)
                e.preventDefault();
        }
        return false;
    }else
    {
        enableKeyDown=false;
        //create the temporary html editor
        var divTemp=edDoc.createElement("DIV");
        divTemp.id='htmleditor_tempdiv';
        divTemp.innerHTML='\uFEFF';
        divTemp.style.left="-10000px"; //hide the div
        divTemp.style.height="1px";
        divTemp.style.width="1px";
        divTemp.style.position="absolute";
        divTemp.style.overflow="hidden";
        edDoc.body.appendChild(divTemp);
        //disable keyup,keypress, mousedown and keydown
        objEditor.contentWindow.document.addEventListener("mousedown",block,false);
        objEditor.contentWindow.document.addEventListener("keydown",block,false);
        enableKeyDown=false;
        //get current selection;
        w=objEditor.contentWindow;
        or=getSel(w).getRangeAt(0);
        //move the cursor to into the div
        var docBody=divTemp.firstChild;
        rng = edDoc.createRange();
        rng.setStart(docBody, 0);
        rng.setEnd(docBody, 1);
        setRange(getSel(w),rng);
        originText=objEditor.contentWindow.document.body.textContent;
        if(originText==='\uFEFF')
        {
            originText="";
        }
        window.setTimeout(function()
        {
            //get and filter the data after onpaste is done
            if(divTemp.innerHTML==='\uFEFF')
            {
                newData="";
                edDoc.body.removeChild(divTemp);
                return;
            }
            newData=divTemp.innerHTML;
            // Restore the old selection
            if (or)
            {
                setRange(getSel(w),or);
            }
            newData=filterPasteData(newData);
            divTemp.innerHTML=newData;
            //paste the new data to the editor
            objEditor.contentWindow.document.execCommand('inserthtml', false, newData );
            edDoc.body.removeChild(divTemp);
        },0);
        //enable keydown,keyup,keypress, mousedown;
        enableKeyDown=true;
        objEditor.contentWindow.document.removeEventListener("mousedown",block,false);
        objEditor.contentWindow.document.removeEventListener("keydown",block,false);
        return true;
    }
}

这里的pasteClipboardData是用作onpaste回调函数的。要使用它,可以通过下面的代码把它加到HTML编辑器的iframe的onpaste事件上。

复制代码

var ifrm=document.getElementById("editor")
if(isIE)
{
    ifrm.contentWindow.document.documentElement.attachEvent("onpaste", function(e){return pasteClipboardData(ifrm.id,e);});
}
else
{
    ifrm.contentWindow.document.addEventListener("paste", function(e){return pasteClipboardData(ifrm.id,e);},false);
}

这里的filterPasteData函数就是专门用来做过滤的函数,具体要怎么去过滤纯文本、HTML及Word数据,将在下一篇讲解。

本文转载于:https://www.jb51.net/article/23717.htm 如有侵犯,请联系zhengruancom@outlook.com删除。
免责声明:正软商城发布此文仅为传递信息,不代表正软商城认同其观点或证实其描述。

热门关注