
Add HTML Editor to Portlet
Security Precaution #
Allowing users to embed HTML on your site is risky! XSS and Phishing attacks become possible, so it is important that any HTML permissions are only given to trusted users.
Introduction #
If you are building a portlet that takes in user input, you may be interested in adding a WYSIWYG HTML editor to your portlet. Using the portal's existing tags, it doesnt take much to add this. Here are the steps to take:
Getting access to the Portals Tags in your JSP#
You must add these lines to your JSP before you can start using the Portal's tags
<%@ taglib uri="http://java.sun.com/portlet" prefix="portlet" %> <%@ taglib uri="http://liferay.com/tld/ui" prefix="liferay-ui" %>
Adding the Editor#
We will be adding two lines of code. The first line will add the actual WYSIWYG editor. The second line of code is a hidden input field which will store the actual html code of the wysiwyg content. You may or may not need the second line depending on how you are using this WYSIWYG editor. If you need the value of the WYSIWYG editor to be submitted with a form, then you will need this line. However, if you are just using javascript to parse the value (and perhaps sending it via ajax), then you will not need this hidden field.
<liferay-ui:input-editor /> <input name="<portlet:namespace />htmlCodeFromEditorPlacedHere" type="hidden" value="" />
Adding Javascript#
By default, the editor will call "initEditor()" to try and pre-populate the body of the editor. In this example, when the editor loads, it will have the value of "scott was here" in bold.
The second method is used to pull out the html code from the editor. One common way to use this method is to attach it to your "save/submit" button so that the value in the wysiwyg editor will be copied into the hidden input field just before the form is submitted.
<script type="text/javascript"> function <portlet:namespace />initEditor() { return '<font style="font-weight: bold">scott was here</font>'; } function <portlet:namespace />extractCodeFromEditor() { var x = document.<portlet:namespace />fm.<portlet:namespace />htmlCodeFromEditorPlacedHere.value = window.<portlet:namespace />editor.getHTML(); alert(x); } </script>