Inserting text at cursor

From MozillaZine Knowledge Base

(Difference between revisions)

Asqueella (Talk | contribs)
(move from Dev:Tips)
Next diff -->

Revision as of 13:01, 4 October 2004

Note: This is only tested with Firefox 0.9.1+, but should work with everything else. Change this note if it works for you ;)


How do I insert some text at cursor position, just as if user typed it?


Let's say you have a focused <textbox> in current document. The following function will insert aText string at the cursor position.

function insertText(aText) {
  try {
    var command = "cmd_insertText";
    var controller = document.commandDispatcher.getControllerForCommand(command);
    if (controller && controller.isCommandEnabled(command)) {
      controller = controller.QueryInterface(Components.interfaces.nsICommandController);
      var params = Components.classes[";1"];
      params = params.createInstance(Components.interfaces.nsICommandParams);
      params.setStringValue("state_data", aText);
      controller.doCommandWithParams(command, params);
  catch (e) {
    dump("Can't do cmd_insertText! ");

Known restriction: <textbox> must be focused. If it isn't, you have to focus it temporarily.