How do you safely push a user influenced url to the DOM, namely to the src
attribute of an img
?
<img>
won't execute anything else than a valid img and scripting in svg is limited. Casual onload
tricks won't work aswell because the input is quoted. Is this enough to ensure a safe DOM insertion via img?
The snippet is simplified, there are checks for url
being a valid url.
Edit: something like http://foo" onerror="alert('XSS')" "
is not a valid url, see here: http://foo" onerror="alert('XSS')" ". You can assume that url
is for sure a valid url. See https://en.wikipedia.org/wiki/Percent-encoding#Types_of_URI_characters, Check if a Javascript string is a url and https://jsfiddle.net/mppkgd7u/
var user = 'random/url/path'; // any kind of user generated string
var url = 'http://' + user; // guaranteed to be url
document.getElementById('view').innerHtml = '<img src="'+url+'">';
console.log(document.getElementById('view').innerHtml);
<div id=view>
</div>