Search code examples
applescriptjavascript-automation

JXA: Get just-clicked on window (in focus window)


Using Javascript for Automation (JXA) I want to identify the window the user has just clicked on. In other words, I want to identify the window that has just come to the front. How can I do that?

So far, I identify the front application, and try to get the window of that application which is in focus, like so:

var frontAppName = Application("System Events").processes.whose({frontmost: {'=': true }})[0].name();  
var frontApp = Application(frontAppName); 
var theCurrentWindow = frontApp.windows[0]

This successfully identifies the application in focus, but frontApp.windows[0] is not quite right, because it is tied to the first window the application originally opened, whether or not that window is in front. (In applescript, "window 1" would probably work, but I'm hoping for a JXA solution.)

So, if I have several windows opened in an application, I need a way to identify which one I am clicking on. How can I do that?


Solution

  • It is known bug of JXA. You can solve issue using abilities of AppleScript execution from JXA code. Following script will return front window of frontmost application:

    (() => {
        'use strict';
    
        // evalAS :: String -> IO String
        const evalAS = s => {
            const
                a = Application.currentApplication(),
                sa = (a.includeStandardAdditions = true, a);
            return sa.doShellScript(
                ['osascript -l AppleScript <<OSA_END 2>/dev/null']
                .concat([s])
                .concat('OSA_END')
                .join('\n')
            );
        };
    
        var frontAppName = Application("System Events").processes.whose({frontmost: {'=': true }})[0].name();  
        var frontApp = Application(frontAppName);
        return evalAS('tell application \"' + frontAppName + '\" to front window');
    
    })();