使用document.body.innerHTML.replace有多安全? [英] How safe is it use document.body.innerHTML.replace?

查看:512
本文介绍了使用document.body.innerHTML.replace有多安全?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

正在运行如下:

document.body.innerHTML = document.body.innerHTML.replace('old value','new value')

document.body.innerHTML = document.body.innerHTML.replace('old value', 'new value')

危险?

我担心也许某些浏览器可能搞砸了整个页面,因为这是JS代码这将放在我无法控制的网站上,谁可能会被谁知道我有点担心的浏览器访问过。

I'm worried that maybe some browsers might screw up the whole page, and since this is JS code that will be placed on sites out of my control, who might get visited by who knows what browsers I'm a little worried.

我的目标只是寻找一个在整个身体中出现一个字符串并替换它。

My goal is only to look for an occurrence of a string in the whole body and replace it.

推荐答案

绝对有潜在危险 - 特别是如果您的HTML代码很复杂,或者如果它是别人的HTML代码(即它的CMS或你创建的可重用的javascript)。此外,它将销毁您在页面上的元素上设置的任何事件监视器。

Definitely potentially dangerous - particularly if your HTML code is complex, or if it's someone else's HTML code (i.e. its a CMS or your creating reusable javascript). Also, it will destroy any eventlisteners you have set on elements on the page.

使用XPath查找文本节点,然后直接替换它。

Find the text-node with XPath, and then do a replace on it directly.

这样的事情(根本没有测试):

Something like this (not tested at all):

var i=0, ii, matches=xpath('//*[contains(text(),"old value")]/text()');
ii=matches.snapshotLength||matches.length;
for(;i<ii;++i){
  var el=matches.snapshotItem(i)||matches[i];
  el.wholeText.replace('old value','new value');
}

其中 xpath()是一个自定义的跨浏览器xpath函数:

Where xpath() is a custom cross-browser xpath function along the lines of:

function xpath(str){
  if(document.evaluate){
    return document.evaluate(str,document,null,6,null);
  }else{
    return document.selectNodes(str);
  }
}

这篇关于使用document.body.innerHTML.replace有多安全?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆