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》
新闻热点
疑难解答