[英]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.然后执行 JavaScript。 How to prevent executing?如何防止执行? Is it possible?可能吗?
You have to strip the script
tags from your HTML string.您必须从 HTML 字符串中去除script
标签。
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.这适用于 Firefox/Chrome,虽然我不知道其他浏览器。 Note this will only work with well-formed (x)html.请注意,这仅适用于格式良好的 (x)html。
EDIT: If you also want the JS, you can amend the previous code thus:编辑:如果你还想要 JS,你可以修改以前的代码:
var scripts = [];
$('script', doc).remove().each(function() {
scripts.push($(this).html());
});
Mind you, you don't even have to remove the script
tags.请注意,您甚至不必删除script
标签。 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.现在响应位于其单独的 DOM 文档中,它不会弄乱您自己的脚本,并且您可以使用简单$('selector', doc)
jQuery 访问您需要的任何内容。
Consider an alternative way to neutralize JavaScript inclusions.考虑另一种中和 JavaScript 夹杂物的方法。 Below is a simple function to prepare a html to be added to the document:下面是一个简单的 function 准备一个 html 添加到文档中:
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 .这里有详细描述 - JavaScript: How to prevent JavaScript within a html being added to the DOM 的执行。 I tested in Chrome, IE and FireFox.我在 Chrome、IE 和 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>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.