I need to decode html in javascript. e.g.:
var str = 'apple & banana';
var strDecoded = htmlDecode(str); // I expect 'apple & banana'
There is no guarantee that the given str is already encoded and common jquery and DOM tricks are XSS vulnerable:
var attackStr = '&</textarea><img src=x onerror=alert(1)>ハローワールド'; // if you see 1 alerted, it means it is XSS vulnerable
var strDecoded; // I wish to get: &</textarea><img src=x onerror=alert(1)>ハローワールド
strDecoded = $('<div/>').html(attackStr).text(); // vulnerable in all browsers
strDecoded = $('<textarea/>').html(attackStr).text(); // vulnerable in ie 9 and firefox
var dv = document.createElement('div');
dv.innerHTML = attackStr; // vulnerable in all browsers
strDecoded = dv.innerText;
var ta = document.createElement('textarea');
ta.innerHTML = attackStr; // vulnerable in ie 9 and firefox
strDecoded = ta.value;
Is there any XSS-safe way to html-decode?