1

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.

ShooTerKo
  • 2,242
  • 1
  • 13
  • 18
tytho
  • 237
  • 2
  • 10
  • 2
    "Terminal.windows.at(0).tabs is essentially an array" -- This is incorrect. It's actually a query object ("object specifier") describing a one-to-many relationship between a window object and its tab objects. (JXA's implementation is FUBAR, its documentation lies, and Apple support for users virtually non-existent. Welcome.) Though on this occasion the real culprit is Terminal's crappy Apple event interface: its `make` command is totally broken and has been for years. So you'll either have to resort to GUI Scripting, or else get yourself a better terminal emulator app like iTerm. Sorry. – foo Dec 14 '14 at 00:37

3 Answers3

1

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)
Cyrus Ngan
  • 199
  • 1
  • 6
1

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'});
koyeung
  • 134
  • 1
  • 2
0

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