1

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?

2
  • 6
    Actually, 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? Commented 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. Commented May 28, 2011 at 2:10

2 Answers 2

1

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.

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

Comments

0

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>

3 Comments

Hmm, don't parse HTML with Regex? Please?
I know it is nasty. However it works quite well. It is copied straight from the prototype source code. Doing it this way means that will work with malformed XHTML and will also work in all browsers.
Good idea. I have removed these tags, but an another way.

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.