首页 > 开发 > HTML > 正文

innerHTML应用

2020-09-18 22:22:55
字体:
来源:转载
供稿:网友

blank的blog:http://www.planabc.net/

innerhtml 属性的使用非常流行,因为他提供了简单的方法完全替代一个 html 元素的内容。另外一个方法是使用 dom level 2 api(removechild, createelement, appendchild)。但很显然,使用 innerhtml 修改 dom tree 是非常容易且有效的方法。然而,你需要知道 innerhtml 有一些自身的问题:

  1. 当 html 字符串包含一个标记为 defer 的 script 标签(<script defer>…</script>)时,如 innerhtml 属性处理不当,在 internet explorer 上会引起脚本注入攻击。
  2. 设置 innerhtml 将会破坏现有的已注册了事件处理函数的 html 元素,会在某些浏览器上引起内存泄露的潜在危险。

还有几个其他次要的缺点,也值得一提的:

  1. 你不能得到刚刚创建的元素的引用,需要你手动添加代码才能取得那些引用(使用 dom apis)。
  2. 你不能在所有浏览器的所有 html 元素上设置 innerhtml 属性(比如,internet explorer 不允许你在表格的行元素上设置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》

上一篇:innerHTML的认识

下一篇:IE6实现min-width

发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表