Inserting text at cursor: Difference between revisions

From MozillaZine Knowledge Base
Jump to navigationJump to search
m (1.0PR-compatible)
mNo edit summary
Line 1: Line 1:
{{extdev}}
''Note: This is only tested with Firefox 0.9/1.0PR, but should work with everything else. Change this note if it works for you ;)''
''Note: This is only tested with Firefox 0.9/1.0PR, but should work with everything else. Change this note if it works for you ;)''


Line 26: Line 28:


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

Revision as of 03:17, 19 December 2004

This page is part of the extension development documentation project.

Ask your questions in MozillaZine Forums. Also try browsing example code.

Note: development documentation is in process of being moved to Mozilla Development Center (MDC).

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

Problem

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

Solution

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["@mozilla.org/embedcomp/command-params;1"];
      params = params.createInstance(Components.interfaces.nsICommandParams);
      params.setStringValue("state_data", aText);
      controller.doCommandWithParams(command, params);
    }
  }
  catch (e) {
    dump("Can't do cmd_insertText! ");
    dump(e+"\n")
  }
}

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