blank的blog:http://www.planabc.net/
innerhtml 屬性的使用非常流行,因為他提供了簡單的方法完全替代一個 html 元素的內容。另外一個方法是使用 dom level 2 api(removechild, createelement, appendchild)。但很顯然,使用 innerhtml 修改 dom tree 是非常容易且有效的方法。然而,你需要知道 innerhtml 有一些自身的問題:
還有幾個其他次要的缺點,也值得一提的:
我更關注與使用 innerhtml 屬性相關的安全和內存問題。很顯然,這不是新問題,已經有能人圍繞這些中的某些問題想出了方法。
douglas crockford 寫了一個 清除函數 ,該函數負責中止由于 html 元素注冊事件處理函數引起的一些循環引用,并允許垃圾回收器(garbage collector)釋放與這些 html 元素關聯的內存。
從 html 字符串中移除 script 標簽并不像看上去那么容易。一個正則表達式可以達到預期效果,雖然很難知道是否覆蓋了所有的可能性。這里是我的解決方案:
/<script[^>]*>[/s/s]*?<//script[^>]*>/ig
現在,讓我們將這兩種技術結合在到一個單獨的 setinnerhtml 函數中,并將 setinnerhtml 函數綁定到 yui 的 yahoo.util.dom 上:
yahoo.util.dom.setinnerhtml = function (el, html) {
el = yahoo.util.dom.get(el);
if (!el || typeof html !== 'string') {
return null;
}
// 中止循環引用
(function (o) {
var a = o.attributes, i, l, n, c;
if (a) {
l = a.length;
for (i = 0; i < l; i += 1) {
n = a[i].name;
if (typeof o[n] === 'function') {
o[n] = null;
}
}
}
a = o.childnodes;
if (a) {
l = a.length;
for (i = 0; i < l; i += 1) {
c = o.childnodes[i];
// 清除子節點
arguments.callee(c);
// 移除所有通過yui的addlistener注冊到元素上所有監聽程序
yahoo.util.event.purgeelement(c);
}
}
})(el);
// 從html字符串中移除script,并設置innerhtml屬性
el.innerhtml = html.replace(/<script[^>]*>[/s/s]*?<//script[^>]*>/ig, "");
// 返回第一個子節點的引用
return el.firstchild;
};
如果此函數還應有其他任何內容或者在正則表達式中遺漏了什么,請讓我知道。
很明顯,在網頁上還有很多其他注入惡意代碼的方法。setinnerhtml 函數僅能在所有 a-grade 瀏覽器上規格化 <script> 標簽的執行行為。如果你準備注入不能信任的 html 代碼,務必首先在服務器端過濾,已有許多庫可以做到這點。
原文:julien lecomte 的 《the problem with innerhtml》
新聞熱點
疑難解答