简体   繁体   中英

Stop executing JavaScript

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?

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.

Consider an alternative way to neutralize JavaScript inclusions. Below is a simple function to prepare a html to be added to the document:

function preventJS(html) {
   return html.replace(/<script(?=(\s|>))/i, '<script type="text/xml" ');
}

How to use:

$("#content").append(preventJS("<span>Hello 1<script type='text/javascript'>alert('Hello 1!');<\/script></span>"));

It's described in details here - JavaScript: How to prevent execution of JavaScript within a html being added to the DOM . I tested in Chrome, IE and FireFox. I hope it will work for you too.

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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM