How to execute a windows command from firefox addo

2019-02-13 21:36发布

问题:

How to execute a windows command and display it's output using firefox addon?

For example: ping www.stackoverfow.com

I am just trying to explore more in firefox addon development by executing a binary file (or) executable packaged together or else running a windows command.

回答1:

You would use nsIProcess for that. In your case things are made more complicated because you don't know which application you want to run - it will usually be c:\windows\system32\ping.exe but you cannot be sure. If you don't want to parse the PATH environment variable yourself you can make the command line shell do it for you:

Components.utils.import("resource://gre/modules/FileUtils.jsm");

var env = Components.classes["@mozilla.org/process/environment;1"]
                    .getService(Components.interfaces.nsIEnvironment);
var shell = new FileUtils.File(env.get("COMSPEC"));
var args = ["/c", "ping stackoverflow.org"];

var process = Components.classes["@mozilla.org/process/util;1"]
                        .createInstance(Components.interfaces.nsIProcess);
process.init(shell);
process.runAsync(args, args.length);

For reference: COMSPEC environment variable, nsIEnvironment.

Note that you cannot receive data back from the process, you can merely get notified when it finishes and learn whether it failed. If you want to get the output of the command you will have to redirect the output to a file (run ping stackoverflow.org > c:\\temp\\foo.txt command via shell) and read out that file afterwards.