javascript-automation

Acitvate a given window in a multi-window application with JXA


Suppose I have two open TextEdit files, and consequently two windows. How can I switch/activate windows programmatically with JXA?

At the moment I have this:

var text = Application("textEdit")
text.activate()
var file1_path = Path("/Users/..../text1.rtf")
var file2_path = Path("/Users/..../text2.rtf")

var doc1 = text.open(file1_path)
var doc2 = text.open(file2_path)

console.log("text1",text.windows["text1.rtf"].index()) //prints 2
console.log("text2",text.windows["text2.rtf"].index()) //prints 1

//the next row brings text1 window to front but doesn't activate it, 
//as a matter of fact the 3 buttons upper/left (close,minimize, full screen) are grey
text.windows["text1.rtf"].index = 1

Solution

  • You can give this a go, which appears to work on High Sierra:

    TextEdit=Application('TextEdit');
    Sys=Application('System Events');
    
    TextEdit.activate()
    
    /* open files, etc. */
    
    Sys.processes["TextEdit"].windows[1].actions['AXRaise'].perform();
    

    And you can, of course, replace the index 1 with the name of the window, such as "text1.rtf".