Inserting text at cursor: Difference between revisions

From MozillaZine Knowledge Base
Jump to navigationJump to search
mNo edit summary
(moved to devmo)
 
Line 1: Line 1:
{{extdev}}
See [http://developer.mozilla.org/en/docs/Code_snippets:Miscellaneous#Inserting_text_at_the_cursor Code snippets: Miscellaneous - Inserting text at the cursor] at [http://developer.mozilla.org MDC].


==Problem==
[[Category:Redirects]]
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 <tt>aText</tt> string at the cursor position.
 
<pre>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")
  }
}</pre>
 
Known restriction: <textbox> must be focused. If it isn't, you have to focus it temporarily.
 
[[Category:Example code|Inserting text at cursor]]

Latest revision as of 18:52, 25 May 2007