js用户输入进行转义、反转义,防XSS攻击

正转义:

//HTML转义
function HTMLEncode(html) {
    var temp = document.createElement("div");
    (temp.textContent != null) ? (temp.textContent = html) : (temp.innerText = html);
    return  temp.innerHTML;
}

测试及结果:

var test= "">";
console.log(HTMLEncode(test));//"><script>alert('XSS');</script>

反转义:

//HTML反转义
function HTMLDecode(text) { 
    var temp = document.createElement("div"); 
    temp.innerHTML = text; 
    var output = temp.innerText || temp.textContent; 
    temp = null; 
    return output; 
} 

测试及结果:

var test= "><script>alert('XSS');</script>";
console.log( HTMLEncode(test)); //">

你可能感兴趣的:(javascript,xss,前端)