-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?

3
  • 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. Commented Mar 24, 2015 at 22:27
  • I'm trying to avoid createElement. Commented Mar 24, 2015 at 22:29
  • 2
    Why would you avoid createElement? Commented Mar 24, 2015 at 22:30

2 Answers 2

-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)

Sign up to request clarification or add additional context in comments.

Comments

-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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.