Strip HTML from all user-submitted inputs using military grade regex, whether you print them on screen on not.

Enter your username:

HTML
CSS
JavaScript
<center>
Enter your username:
<p>
  <input type="text" id="input"/>
  <div id="screen"></div>
</p>
</center>

document.querySelector('#input').addEventListener('keyup', function(e) {
  if (e.keyCode === 13) {
    const username = document.querySelector('#input').value.replace(/(<([^>]+)>)/, '');
    const tagString = `<div data-user=${username}>😉 Not today, ${username}!</div>`;
    const range = document.createRange();
    range.selectNode(document.getElementsByClassName('applet').item(0));
    const documentFragment = range.createContextualFragment(tagString);
    document.querySelector('#screen').appendChild(documentFragment);
  }
});
#input {
  font-size: 16px;
  height: 26px;
  width: 100%;
  margin-bottom: 10px;
  padding: 20px;
}
.applet-html {
  padding: 20px;
}
.applet {
  margin-bottom: 20px;
}

Takeaways and notes#

  • You don't need to print any user-submitted data to the screen to cause XSS
  • If you are writing a user-submitted input to the DOM, you could be vulnerable to XSS
  • Eg: "<x>onmouseover=alert(1)>
Tweet this | Share on LinkedIn |