Search code examples
macososascriptjavascript-automation

osascript is very slower than Script Editor


First of all, I admit that I'm starting with a new project with JXA (Javascript automation for mac os) without having much understanding about AppleScript.

Currently, I'm trying to run following command using JXA:

Application("System Events").processes.windows.name()

First, I used Script Editor to run it. It worked fine and I got the output quickly enough.

However, according to my use case, since I want to get the output of this code frequently from one of my bash script, I tried to execute it using osascript as follows

osascript -l JavaScript -e 'Application("System Events").processes.windows.name()' 

But this time, it took few seconds to print the result in the console.

Now my question is why it takes too much time to execute the same script in osascript compare to Script Editor? Is there any way to optimize the performance of it?


Solution

  • Here's the JXA solution:

    var winList = Application("System Events").processes.whose({backgroundOnly: {'=': false} }).windows.name();
    
    var winList2 = winList.reduce(
      function(accumulator, currentValue) {
        return accumulator.concat(currentValue);
      },
      []
    );
    winList2 = winList2.filter(e => (e !== ""));
    winList2.join(',')

    There may be a better JavaScript from those JavaScript masters.