I am working on a project wherein I am using content-editable div, and a library, medium.js But this doesnt prevent script injection. What would be the best way to prevent injection of any kind of script into my div?
-
set permissible values on the backend. avoid 'eval' of arbitrary input. what are you using on the server side? – random-forest-cat Jan 13 '15 at 06:24
-
@lfender6445: Actually, we need to handle this on front-end, because the moment I press Enter, the script gets exectuted. Morever, while rendering too, the script gets executed. – ShivangiBilora Jan 13 '15 at 06:59
2 Answers
I assume you are sending the edited information to a server, storing it in a database so it's saved and rendered later in a website? And that you want to allow users to use certain HTML code in their input?
In that case, you need to implement a "HTML sanitizer" server-side. For PHP there's HTMLPurifier, for Python there's Bleach, Ruby has a sanitize module. Those are just examples, there are more, and you could also (carefully!) write your own sanitizer of course. A sanitizer filters strings so only plain text and HTML tags & attributes are entered into the database, without any script functions. See Wikipedia - HTML Sanitization for ideas on what the best approach might be for you.
Using Javascript filtering when content is edited won't be sufficient, as the attacker can always just post content to your server directly by analyzing your website, leaving code in you database.
You could however allow it in your database and sanitize when content is served (so it will never be displayed), but it would be better to filter it out when it's submitted. If you want to sanitize the to-be-displayed HTML clientside, you can use something like the Google Caja library. If you take that path, be sure to sanitize content in your database if you ever implement a different front-end.
Other options might be to disable HTML input altogether (only allow text, stripping all tags). Or to implement the popular Markdown syntax, like the StackExchange websites and popular sites like Reddit do. The old BBcode methods are always an option in PHP, and it's still quite popular as a rich text input method on forums.

- 2,406
- 1
- 27
- 32
Update the textContent
property on the div, rather than the innerHTML
. How are you currently letting the user edit the content of the div? Can you post some code?

- 1,626
- 9
- 9
-
I am using medium.js library, which has this div initially:Then, when u start typing anything into the div, it becomes:hiiii– ShivangiBilora Jan 13 '15 at 06:44