推扬网

 找回密码
 立即注册

QQ登录

只需一步,快速开始

搜索
推扬网 门户 经验分享 查看内容

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

2020-4-11 13:40| 发布者: admin| 查看: 331| 评论: 0

最近在解决数据粘贴方面取得了不少进展,作为Html在线编辑器所必须具备的技术,在这里详细给大家介绍并提供实现参考。

作者:Tony Qu
最近在解决数据粘贴方面取得了不少进展,作为Html在线编辑器所必须具备的技术,在这里详细给大家介绍并提供实现参考。在研究过程中,我也确实走了不少弯路,尝试了n种方式,由于美国的PM始终觉得有些影响用户体验的东西无法接受,导致好几个提案被否定,不过收获还是很丰富的。
我现在写code喜欢需求驱动,让我们来看看这项技术的主要需求
* 能够过滤用户贴进来的纯文本数据
* 能够过滤用户贴进来的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的权限,javascript脚本是没有权限去设置的,虽然从技术人员来看这是很正常的,但是很多产品经理无法接受这一点,至少我的产品经理是这么认为的。
以下是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.addDataFlavor('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.addDataFlavor('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可以在多个htmleditor之间共用,所以我的实现中仅仅改变了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("<body></body>");
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数据将在下一篇讲解。

鲜花

握手

雷人

路过

鸡蛋

最新评论

精选推荐

    广告服务|投稿要求|禁言标准|版权说明|免责声明|手机版|小黑屋|推扬网 ( 粤ICP备18134897号 )|网站地图 | 邮箱:vayae@hotmail.com

    GMT+8, 2024-3-29 08:21 , Processed in 0.071208 second(s), 28 queries .

    Powered by Discuz! X3.4

    © 2001-2017 Comsenz Inc.

    返回顶部