佳木斯湛栽影视文化发展公司

主頁 > 知識庫 > Html 編輯器粘貼內(nèi)容過濾技術(shù)詳解

Html 編輯器粘貼內(nèi)容過濾技術(shù)詳解

熱門標簽:美圖手機 呼叫中心市場需求 鐵路電話系統(tǒng) 網(wǎng)站文章發(fā)布 服務(wù)器配置 檢查注冊表項 銀行業(yè)務(wù) 智能手機
作者:Tony Qu
最近在解決數(shù)據(jù)粘貼方面取得了不少進展,作為Html在線編輯器所必須具備的技術(shù),在這里詳細給大家介紹并提供實現(xiàn)參考。在研究過程中,我也確實走了不少彎路,嘗試了n種方式,由于美國的PM始終覺得有些影響用戶體驗的東西無法接受,導(dǎo)致好幾個提案被否定,不過收獲還是很豐富的。
我現(xiàn)在寫code喜歡需求驅(qū)動,讓我們來看看這項技術(shù)的主要需求
* 能夠過濾用戶貼進來的純文本數(shù)據(jù)
* 能夠過濾用戶貼進來的html數(shù)據(jù)(未經(jīng)Html編碼)
* 能夠過濾用戶貼進來的Word數(shù)據(jù),并能把大部分Word格式保留下來。
* 在這一過程中盡量不要讓用戶知道我們在做過濾
* 不要去提示用戶是否啟用某種權(quán)限
本例所適用的場景為使用iframe實現(xiàn)的Html編輯器,而不是文本框(textarea或type為text的input)。

在研究過程中,我主要參考了tinymce、ckeditor,但最后我還是選擇了tinymce的實現(xiàn)方法,具體原因在你看完下面這段文字后就會明白。
ckeditor的實現(xiàn)方式是在onpaste事件觸發(fā)時,從剪貼板取出數(shù)據(jù),處理取出的文本,然后再把處理好的文本存入剪貼板。有人說,那我能不能在onpaste中直接取消paste動作,然后自己把獲得的內(nèi)容放入iframe當中去,我當時就干過這事,但結(jié)果卻出人意料,直接從剪貼板拿出的數(shù)據(jù)是不包括格式信息的文本,特別是從Word粘貼過來的數(shù)據(jù),純文本,顏色、布局等數(shù)據(jù)都不存在,這樣的話,你的用戶只能粘貼沒有格式的數(shù)據(jù)過來,然后自己重新在Html編輯器里面編輯。但是如果讓瀏覽器自己去做粘貼,格式信息都會保留,瀏覽器會自動把Word的粘貼數(shù)據(jù)轉(zhuǎn)換為xml數(shù)據(jù),放入dom中。所以為了保留格式信息,我們恐怕只能通過瀏覽器的標準粘貼行為的幫助實現(xiàn)這一點。
另外ckeditor的實現(xiàn)在Firefox中有一個致命的弱點,如果你要從剪貼板讀寫數(shù)據(jù),你就必須提示用戶自己去設(shè)置一個叫signed.applets.codebase_principal_support的權(quán)限,javascript腳本是沒有權(quán)限去設(shè)置的,雖然從技術(shù)人員來看這是很正常的,但是很多產(chǎn)品經(jīng)理無法接受這一點,至少我的產(chǎn)品經(jīng)理是這么認為的。
以下是ckeditor獲取和設(shè)置剪貼板的代碼,供大家參考。
復(fù)制代碼 代碼如下:

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;
}

以下是提示用戶啟用權(quán)限的代碼
復(fù)制代碼 代碼如下:

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的實現(xiàn)方式,我在看它的代碼的時候特別留意到它盡然不需要權(quán)限就能在Firefox下面搞定粘貼,并且還能保留Word格式,于是就仔細閱讀了其中的代碼。tinymce的實現(xiàn)步驟在IE和Firefox下面是不同的:
IE實現(xiàn)
1. 在onpaste回調(diào)函數(shù)中創(chuàng)建一個臨時的iframe,用于粘貼內(nèi)容,這個iframe放在主窗口的body下面即可。
2. 在當前光標位置創(chuàng)建一個Range,用來保存光標位置和選中信息。
3. 讓臨時iframe獲得焦點,執(zhí)行粘貼命令,即document.execCommand(“paste”),內(nèi)容會粘貼在臨時的iframe中
4. 通過innerHTML獲得臨時iframe中的內(nèi)容并進行過濾
5. 讓Html編輯器的iframe獲得焦點,用之前創(chuàng)建的Range對象執(zhí)行pasteHTML方法來粘貼過濾后的內(nèi)容
6. 最后取消默認的paste動作
(臨時iframe可以根據(jù)個人喜好從DOM中刪除,但由于這個iframe可以在多個htmleditor之間共用,所以我的實現(xiàn)中僅僅改變了iframe的left, top來調(diào)整iframe的位置,而不是移除它,調(diào)整left和top的目的在于焦點移到臨時iframe的時候如果Html編輯器的iframe和臨時iframe不在一個視圖之內(nèi),屏幕會滾動,這樣會導(dǎo)致屏幕沒有原因的閃爍。)
Firefox實現(xiàn)
1. 在onpaste回調(diào)函數(shù)中創(chuàng)建一個臨時的div,這個div放在Html編輯器的iframe里面,這也是繞過權(quán)限問題的關(guān)鍵。
2. 保存當前光標和焦點位置,然后將光標移到臨時創(chuàng)建的div中
3. 通過window.setTimeout設(shè)置一個回調(diào)函數(shù)在paste動作瞬間完成之后執(zhí)行
4. 讓paste動作執(zhí)行(onpaste回調(diào)函數(shù)執(zhí)行完畢)
5. 剛才設(shè)置的回調(diào)函數(shù)執(zhí)行,在里面獲得臨時div的innerHTML并進行過濾
6. 恢復(fù)剛才保存的光標和焦點位置,并移除臨時div
7. 通過inserthtml命令(execCommand(“inserthtml”))把過濾后的內(nèi)容貼到Html編輯器的iframe中。

詳細代碼如下:
復(fù)制代碼 代碼如下:

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回調(diào)函數(shù)的,要使用它的話,可以通過下面的代碼把它加到Html編輯器的iframe的onpaste事件上。
復(fù)制代碼 代碼如下:

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函數(shù)就是我們專門用來做過濾的函數(shù),具體要怎么去過濾純文本、html及Word數(shù)據(jù)將在下一篇講解。

標簽:新疆 紅河 滄州 長治 上海 河南 沈陽 樂山

巨人網(wǎng)絡(luò)通訊聲明:本文標題《Html 編輯器粘貼內(nèi)容過濾技術(shù)詳解》,本文關(guān)鍵詞  ;如發(fā)現(xiàn)本文內(nèi)容存在版權(quán)問題,煩請?zhí)峁┫嚓P(guān)信息告之我們,我們將及時溝通與處理。本站內(nèi)容系統(tǒng)采集于網(wǎng)絡(luò),涉及言論、版權(quán)與本站無關(guān)。
  • 相關(guān)文章
  • 收縮
    • 微信客服
    • 微信二維碼
    • 電話咨詢

    • 400-1100-266
    叙永县| 龙州县| 介休市| 岢岚县| 松桃| 平乐县| 茂名市| 比如县| 诏安县| 榕江县| 资中县| 武义县| 九龙县| 武邑县| 万宁市| 永宁县| 桦川县| 江口县| 阜南县| 麻城市| 四会市| 兴宁市| 渝北区| 江口县| 东阳市| 开化县| 镇宁| 时尚| 渝北区| 丹阳市| 潮安县| 临沂市| 许昌市| 泉州市| 宣汉县| 连云港市| 嵊泗县| 达孜县| 商洛市| 迭部县| 玛纳斯县|