Open new Terminal Tab with OS X JavaScript for Automation

2.2k Views Asked by At

I am playing around with JavaScript for Automation on OS X Yosemite.

I am trying to open up a new tab in the terminal application. Here is what I've got so far:

var Terminal = Application('Terminal);
var Tab      = Terminal.Tab;

// Activate the Terminal App, creates a new window if there isn't one already
Terminal.activate();

// This contains all the windows
Terminal.windows;
// This contains the first window
Terminal.windows.at(0) // alternatively, Terminal.windows[0]

// This contains the tabs in the first window
Terminal.windows.at(0).tabs

The Terminal.windows.at(0).tabs is essentially an array. It has a .push method. I assumed that I could use the following statement to add a tab to the window:

Terminal.windows.at(0).tabs.push(new Tab());

but it throws a very general error:

Error -10000: AppleEvent handler failed.

The documentation is severely lacking and I'm thinking that this JavaScript for automation thing was just a gimik to get JavaScript developers onboard.

Note: I've seen AppleScript solutions that essentially just tell the System Events Application to press Command + T to open up a new tab. That feels very hacky and makes Command + T hardcoded in there.

3

There are 3 best solutions below

0
On

You can emulate the shortcut for one new tab. Also need declare the target tab

tell application "System Events" to keystroke "t" using {command down}

Look the example with two or more tabs

teel application "Terminal"
    do script "cd ~/ && ls" in tab 1 of front window
    tell application "System Events" to keystroke "t" using {command down}
    do script "cd ~/Applications && ls" in tab 2 of front window
end tell
0
On

the following code works for chrome and safari, but not work for terminal, I am still figuring out the reason, see if this info helps.

chrome = Application("Google Chrome")
newTab = chrome.Tab()
chrome.windows[0].tabs.push(newTab)
0
On

see if the following work in your case:

var system = Application('System Events');
var terminal = Application('Terminal');

// tell application "Terminal" to activate
terminal.activate();  

// tell application "System Events" to tell process "Terminal" to keystroke "t" using command down
system.keystroke('t', {using: 'command down'});