-2

I'm looking for a non-invasive javascript HTML/CSS/JS injection into page. I'm ideally looking to use document.write, but keep the original contents that were on the page. So doing the following:

javascript:document.write("blablabla"); - this removes all the content on page, I don't want to use innerHTML += to append the data.

Any suggestions?

CBMC
  • 11
  • 4
  • You shouldn't use `document.write`. Use `document.createElement` to create new elements, use the `document.getElement*` functions to query for parent elements to which you'd like to append. Then use that element's `appendChild` function to add your new elements. – Austin Mullins Mar 24 '15 at 22:27
  • I'm trying to avoid createElement. – CBMC Mar 24 '15 at 22:29
  • 2
    Why would you avoid `createElement`? – Evan Davis Mar 24 '15 at 22:30

2 Answers2

-1

If document.write is called after the onload event for the document it needs to re-open the document - effectively truncating it. While you can explicitly call document.write() inline (either with javascript directly embedded in the page or with a tag which does not use defer/async) this is considered bad practice as it blocks all the other processing of the page.

You can inject elements by constructing them in Javascript personally I prefer to set the innerHTML of an existing placeholder to an HTML fragment:

<div id='placeholder/></div>
...
document.getElementById('placeholder').innerHTML="<h2>hello world!</h2>";

(using createElement becomes messy and slow when creating/injecting complex HTML)

Community
  • 1
  • 1
symcbean
  • 47,736
  • 6
  • 59
  • 94
-2

document.write will always overwrite the whole page as far I know. One option is to append/prepend your code to a div or to the bottom of your body.

$(elementObj).append(contents);
//or
$(elementObj).prepend(contents);

You can createElement() then use one of the methods above to inject your code into the newly created element.

atomCode
  • 842
  • 7
  • 17