I am trying to render HTML as it is typed. That is, a user types HTML into a textarea and it is rendered (using javascript, I think) in a Literal or another textarea or perhaps a window within the window. Otherwise, I have to make them type it all in and then click a preview button.
Take the input of the text area and assign it to the inner html of a div tag onKeyPress of the text area.
Some reasons I wouldn't want to do it real time, but instead with a preview as you note (be it in JavaScript or a server side language)
- Unintentionally, their code could break your page (extra closed div in their code to break yours)
- Intentionally, their code could break your page
- You would have to sanitize their tags and class names
- You should consider not allowing script
- You need to trap for HTML Encoded entries as well as tags or other input format
- Security regarding who is entering what code on what page and where
- XSS issues (making your tool an attack vector on other sites)
So while that is a cool feature, there are probably just a beginning list of things to consider before you take it on. This list has always been enough for me to avoid the real time thing.
One solution that is a little bit safer is to send all of the data in a form post to a server side script that renders the html page. Then load that asynchronously in an iframe when they click the preview button. If you choose to do this as it is being typed there will be a lot of useless round trips to the server, not to mention page loads that affect the history stack.
I have a working example: http://www.galactic-warz.org/BBCodeTest.php
You enter your message in the textarea (first field). The message is transformed. A big list of BBCodes is converted into SAFE HTML, bad HTML is deleted, good HTML is kept, JS event attributes are deleted. The output message is printed in a div (second field), which makes it render all HTML live. You can then do what you want with the output (except edit it).
It is very safe. All HTML output is safe HTML, JS event attributes are deleted, and it will not close the div when entering (or the BBCode [/div]). The last thing went automatically, no coding done for this.
On a second notice, this editing thing we write the answers in has exactly the same basics...
Youri