Sometimes the page will have an input box, the user input content will be displayed in the page, similar to the web chat application. If the user enters a JS script, the scale: <script>alert (' Test '); </script>, the page pops up a dialog box, Or the input of the script to change the page JS variable code will be when the program is abnormal or to achieve the purpose of skipping some kind of verification. So how to prevent this malicious JS script attack? This problem can be solved by HTML escape.
One: What is HTML escape?
HTML Escape is the conversion of special characters or HTML tags to the corresponding characters. If:< is escaped to <> or escaped to > like "<script>alert (' Test ');</script>" This character will be escaped as: "<script>alert (' test '); </script> "again when the page will be < resolution to <,> resolution to, thereby restoring the user's true input, the final display on the page or" <script>alert (' test '); </ Script> ", that is to avoid the JS injection attack and the real display of user input.
Two: How to escape?
1, through JS implementation
The innerHTML content of the escape element is the escaped character
function HtmlEncode (str) {
var ele = document.createelement (' span ');
Ele.appendchild (document.createTextNode (str));
return ele.innerhtml;
}
Parse
function HtmlDecode (str) {
var ele = document.createelement (' span ');
ele.innerhtml = str;
return ele.textcontent;
}
2, through jquery implementation
function Htmlencodejq (str) {return
$ (' <span/> '). Text (str). HTML ();
function Htmldecodejq (str) {return
$ (' <span/> '). html (str). text ();
3. Use
var msg=htmlencodejq (' <script>alert (' test ');</script> ');
$ (' body '). Append (msg);
It is recommended to use jquery because of better compatibility.
The above article on HTML escape and prevent JavaScript injection attack is a small series to share all the content, hope to give you a reference, but also hope that we support the cloud habitat community.