简体   繁体   English

如何防止文本中的脚本标记执行?

[英]How to prevent script tags in text from executing?

I had a text box in my browser. 我的浏览器中有一个文本框。 Whatever you typed in the text box and clicked on okay button, the text submitted server through a AJAX request and then spread that message to remaining people, including to me also. 无论你在文本框中输入什么并点击了okay按钮,文本都会通过AJAX请求提交服务器,然后将该消息传播给剩下的人,包括我。

The message is appeared on a <div> . 消息出现在<div>

What's my problem is if I typed html or script tags in that message they are not appearing in the message <div> and they are executing . 我的问题是,如果我在该消息中键入html或脚本标记,它们不会出现在消息<div>并且它们正在执行。

If I typed like tags opened and end with script in that middle code is executing on client side, how can I prevent executing and I am able to spread <script> tags also in the messages spreading to all. 如果我输入类似标签打开并以脚本结束,因为中间代码正在客户端执行,我该如何防止执行,并且我也能够在传播给所有人的消息中传播<script>标签。

Have you tried replacing with html character entities? 您是否尝试过替换html字符实体? For example replacing all < with &lt; 例如,替换所有< with &lt; .

If you want the text to always be text, treat is as text and don't use it to set innerHTML property for example. 如果您希望文本始终为文本,则视为文本,并且不要使用它来设置innerHTML属性。

Update text nodes instead. 改为更新文本节点。

Update 更新

For example, if you had user input in userInput , and you wanted to display it, you would treat it as text, not HTML. 例如,如果您在userInput有用户输入,并且想要显示它,则将其视为文本而不是HTML。

var element = document.body,
    // For example
    userInput = "Alex <script>alert('xss')</script>";

// Don't do this! Your input is text, not HTML.
// element.innerHTML = userInput;

// Use this instead
if ('textContent' in element) {
    element.textContent = userInput;
} else {
    element.innerText = userInput;
}

jsFiddle . jsFiddle

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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