2011-07-26 49 views
2

如果已經沒有運行,我想讓Javascript運行說cmd.exe。如果它尚未運行,請讓javascript運行一個進程

我希望有一種方法可以讓JavaScript看看正在運行的進程,然後如果名稱在列表中不運行。但如果它沒有運行的過程。

+2

你可能想看看JScript.net。 –

+1

或者查看Rhino,ringoJS,nodejs或任何其他服務器端js平臺。雖然對於Windows,JScript.NET將是最好的 – Raynos

+1

以及WSH對象模型:http://msdn.microsoft.com/en-us/library/a74hyyw0(v=vs.85).aspx – JAAulde

回答

6

JavaScript不是編寫OS級過程控制腳本的最佳途徑。如果javascript能夠直接訪問您的操作系統,那麼瀏覽互聯網會帶來極大的安全風險。

Internet Explorer確實有一個機制來從JavaScript腳本Windows,但您將不得不調整您的安全設置,以允許這發生。其他瀏覽器甚至不提供這種可能性。

此代碼將在Internet Explorer中運行的notepad.exe,選擇「允許阻止的內容」從安全警告之後:

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

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

因此,我們可以用這個方法來這兩個列表活動進程啓動一個,如果它是合適的:

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'); 

保持我這是一個概念的證明 - 在實踐中,我不會建議你永遠不要這樣做。它是瀏覽器特定的,危險的,可利用的,並且通常是不好的做法。 Web語言適用於Web應用程序,儘管Microsoft可能想告訴您,但JavaScript並不打算成爲OS腳本語言。 :)

相關問題