简体   繁体   中英

HTML / Javascript: Should I encode, escape, or sanitize user-generated strings for alt attributes (<img/> tags)?

There seems to be many accepted answers regarding if one needs to encode user-generated HTML attributes (the alt attribute of an image for instance), 'escape' them, or 'sanitize' them.

I am wondering: If I am rendering user-generated alt attributes for img elements, how should I encode them (if at all), should I both encode and sanitize? Should I both sanitize and escape?

If I know any character has the possibility of showing up how should I process this user-generated string before setting it as an alt attribute?

I am using React.js to generate the markup in which this user-generated string is being used as an alt attribute of an img tag

Assuming you mean that you have something along the lines of:

<img alt={this.props.alt} />

… then no, you don't need to do anything. React works on the DOM. You aren't generating HTML source code, so special characters in the data can't be used to inject JavaScript through an XSS vulnerability.

Sanitizing is required so there are no issues with displaying the string. If you are storing the alt attribute in a database then yyou should definitely escape the string.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM