0

I am looking for a way to inject arbitrary html snippets into a DOM node.

The reason I am asking is because I am developing some functionality for retargeting/tracking tags and my advertising partners use different approaches.

Some of them use script tags and they behave differently from other tags.

I have discovered that simply setting the innerHTML property on an arbitrary DOM node to the string <script src="foo"></script> is not going to work. Sure the tag is injected, but the code is not evaluated. I have to create a script node first, then set the src and type attributes and finally inject them.

I am looking for an approach to analyze HTML snippets and automatically and safely detect the correct/optimal way to inject them. I've already got jQuery, but if there are any libraries out there to make this easier, I'm happy to consider them.

2
  • How about some code to explain what you'd like to do: "analyze HTML snippet and automatically detect the optimal way to inject" is not very clear. Many browsers prevent you from setting innerHTML to a script tag to prevent XSS. So if by arbitrary, you mean, set it to a script tag, you shouldn't allow that. You should treat setting HTML and scripts differently Commented Jun 21, 2014 at 17:32
  • If you inject a script tag, I think you would expect that code to be run. If browsers do not want you to run external scripts after the page has loaded, it makes little sense why creating a script element and appending it to a node works, while overwriting the innerHTML of the same node does not. I would like to create an API that allows me to inject snippets agnostically of such quirks. Commented Jun 21, 2014 at 17:38

1 Answer 1

1

Googling for "jQuery html string to elements", gave me: http://api.jquery.com/html/#html2

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

2 Comments

I just tested the method with an external script and it works so far.
Well let us now if it does the job :)

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.