I have:
$('body').data('data1', '<script type="text/javascript">console.debug('execute');</script><div>example</div>');
and:
<div id="content"></div>
when I do:
$(document).ready(function () {
$('#content').html($('body').data('data1'));
});
then JavaScript is executed. How to prevent executing? Is it possible?
-
6Actually, you get a syntax error. And even if you fix that, what did you expect to happen? If you don't want a script to run, then why are you inserting it into the DOM?Lightness Races in Orbit– Lightness Races in Orbit2011年05月28日 02:01:43 +00:00Commented May 28, 2011 at 2:01
-
Sorry for this syntax error. I was writing from memory. This example is the sample of a large problem. Just I must also store JS codes.Paweł Walaszek– Paweł Walaszek2011年05月28日 02:10:54 +00:00Commented May 28, 2011 at 2:10
2 Answers 2
You have to strip the script tags from your HTML string.
var p = new DOMParser(),
doc = p.parseFromString("<html><body>...</body></html>", "text/xml");
$('script', doc).remove();
This works with Firefox/Chrome, although I don't know about other browsers. Note this will only work with well-formed (x)html.
EDIT: If you also want the JS, you can amend the previous code thus:
var scripts = [];
$('script', doc).remove().each(function() {
scripts.push($(this).html());
});
Mind you, you don't even have to remove the script tags. Now that the response is in its separate DOM document, it will not mess up your own scripts, and you can access whatever content you need from it using easy $('selector', doc) jQuery.
Comments
The only way you are going to stop the script from executing is to remove it from your data. The prototype framework does this using a regular expression like below:
<script[^>]*>([\\S\\s]*?)<\/script>