Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How safe is it use document.body.innerHTML.replace?

Tags:

javascript

Is running something like:

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

dangerous?

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.

like image 729
MB. Avatar asked Jul 23 '10 16:07

MB.


2 Answers

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.

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

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);
  }
}
like image 165
lucideer Avatar answered Sep 22 '22 01:09

lucideer


I agree with lucideer, you should find the node containing the text you're looking for, and then do a replace. JS frameworks make this very easy. jQuery for example has the powerful :contains('your text') selector

http://api.jquery.com/contains-selector/

like image 34
Java Drinker Avatar answered Sep 20 '22 01:09

Java Drinker