How to create a rich text or HTML WYSIWYG type editor in Mozilla has come up a few times so I thought a post was in order. Mozilla has a rich text editing system (called Midas) and an API similar to Internet Explorer’s. Mozilla, like Internet Explorer, supports the ability to make an entire document editable by setting the designMode
property of the document object. Once in design mode, the document can be manipulated using various DHTML commands.
The API for interacting with the document is:
- document.execCommand – Executes the given command.
- document.queryCommandEnabled – Determines whether the given command can be executed on the document in its current state.
- document.queryCommandIndeterm – Determines whether the current selection is in an indetermined state.
- document.queryCommandState – Determines whether the given command has been executed on the current selection.
- document.queryCommandValue – Determines the current value of the document, range, or current selection for the given command.
The most typical way to create a rich text editor in a XUL document is to use the
element. In an HTML document, you would use the element:
XUL:
HTML:
You use JavaScript to turn on design mode:
var editor; /* global var */
function onload() {
editor = document.getElementById("edit");
editor.contentDocument.designMode = "on";
setTimeout(function() { editor.contentWindow.focus(); }, 100);
}
window.addEventListener("load", onload, false);
You use the API to send commands to the document:
function toggleBold() {
editor.contentDocument.execCommand("bold", false, null);
}
function toggleItalic() {
editor.contentDocument.execCommand("italic", false, null);
}
function alignLeft() {
editor.contentDocument.execCommand("justifyleft", false, null);
}
function alignRight() {
editor.contentDocument.execCommand("justifyright", false, null);
}
I found a document that discusses the differences between the Mozilla and Internet Explorer rich editing systems.
I created simple XUL and HTML clippings to demonstrate the system. You can open the HTML clipping in a Mozilla compatible browser. You can download the XUL clipping and open it in XUL Explorer. Right-click on the link and pick “Save Link As” to save it to your machine.