Using spell checking in XUL

Spell checking functionality is available starting in Firefox 2. This document describes how to use the mozISpellCheckingEngine component to add spell checking capabilities to your Firefox extension.

See Controlling spell checking in HTML forms for details on adding spell check support to HTML forms for your website.

Checking the spelling of a word

To check the spelling of a word, you must first create an interface to the mozISpellCheckingEngine component and then call the check() method on the string you wish to test. This method returns true if the word is correctly spelled, or false if it's not.

You may also want to check to see if the word is in the user's personal dictionary, since sometimes a word might be correctly spelled but in the dictionary.

// Different versions of Firefox have different contract IDs
var spellclass = "@mozilla.org/spellchecker/myspell;1";
if ("@mozilla.org/spellchecker/hunspell;1" in Components.classes)
	spellclass = "@mozilla.org/spellchecker/hunspell;1";
if ("@mozilla.org/spellchecker/engine;1" in Components.classes)
	spellclass = "@mozilla.org/spellchecker/engine;1";
	
gSpellCheckEngine = Components.classes[spellclass].getService(Components.interfaces.mozISpellCheckingEngine);
gSpellCheckEngine.dictionary = 'en-US';

if (gSpellCheckEngine.check("kat"))
{
    // It's spelled correctly
}
else
{
    // It's spelled incorrectly but check if the user has added "kat" as a correct word..
    var mPersonalDictionary = Components.classes["@mozilla.org/spellchecker/personaldictionary;1"]
                                .getService(Components.interfaces.mozIPersonalDictionary);
    if (mPersonalDictionary.check("kat", gSpellCheckEngine.dictionary))
    {
        // It's spelled correctly accourdly to user personal dictionary
    }
    else
    {
        // It's spelled incorrectly
    }
}							

Getting a list of suggestions

To get a list of suggestions for a misspelled word, you call the suggest() method, specifying the word and an object to be filled with an array of possible suggestions.

var suggestions = {};
gSpellCheckEngine.suggest("kat", suggestions, {});

if (suggestions.value) {
   // suggestions.value is a JavaScript Array of strings
   // there were suggestions.value.length suggestions found
}