Getting javascript to run a process if it's not already running

限于喜欢 提交于 2019-12-22 11:21:26

问题


I want to have Javascript run say cmd.exe if there is already not one running.

I was hoping there is a way to have javascript look at running processes and then if the name is in the list dont run. but if it's not run the process.


回答1:


Javascript is not the best route for scripting OS-level process control. If javascript were able to have such direct access to your operating system, it would be an extreme security risk to ever browse the internet.

Internet Explorer does have a mechanism to script Windows from javascript, but you would have to adjust your security settings to allow this to occur. Other browsers do not even offer the possibility.

This code will execute notepad.exe in Internet Explorer, after choosing to "Allow blocked content" from the security warning:

var shell = new ActiveXObject('WScript.Shell');
shell .Run("notepad.exe");

docs: http://msdn.microsoft.com/en-us/library/aew9yb99%28v=vs.85%29.aspx

So, we can use this method to both list active processes and to start one if it is appropriate:

function startUniqueProcess(process_name, process_path) {
    // create a shell object and exec handle
    var shell = new ActiveXObject('WScript.Shell');
    var handle = shell.Exec("tasklist.exe");

    // loop through the output of tasklist.exe
    while (!handle.StdOut.AtEndOfStream) {
        // grab a line of text
        var p = handle.StdOut.ReadLine();
        // split on space
        p = p.split(' ');
        // check for split lines longer than 2
        if (p.length < 2)
            continue;
        // match process_name to this item
        if (p[0] == process_name) {
            // clean up and return false, process already running
            shell = null;
            handle = null;
            return false;
        } // end :: if matching process name
    } // end :: while

    // clean up
    handle = null;

    // process not found, start it
    return shell.Exec(process_path);
}


// example use
var result = startUniqueProcess('notepad.exe', 'notepad.exe');
if (result === false)
    alert('did not start, already open');
else
    alert('should be open');

Keep in mind, this is proof of a concept - in practice I would not suggest you ever, ever, ever do this. It is browser-specific, dangerous, exploitable, and generally bad practice. Web languages are for web applications, javascript is not intended to be a OS scripting language despite what Microsoft might want to tell you. :)



来源:https://stackoverflow.com/questions/6833419/getting-javascript-to-run-a-process-if-its-not-already-running

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!