2

I'd like to use Python and appscript to set a given Google tab as the foremost tab. I can acquire the tab thusly:

from appscript import *
chrome = app('Google Chrome')
tab_title = 'New York Times'
win_tabs = []
for win in chrome.windows.get():
    win_tabs.append([])
    tnames = map(lambda x: x.title(), win.tabs())
    rel_t = [t for t in win.tabs() if tab_title in t.title()]
    if len(rel_t):
        rel_t = rel_t[0]
        break

Now, I'd like to set that tab as the front-most window. Any ideas? I suspect I'd have to use something like

se = app('System Events')

And manage things from there, but I've no idea.

Mogsdad
  • 44,709
  • 21
  • 151
  • 275
eriophora
  • 999
  • 1
  • 8
  • 20

1 Answers1

1

You can use win.active_tab_index.set(number) to change the active tab. No need for system events. But the tab object doesn't have a reference to its own index, so change it to this (edit: rewrote to avoid a bug)

def activate_chrome_tab(title):
    for window in chrome.windows.get():
        for index, tab in enumerate(window.tabs()):
            if title in tab.title():
                window.active_tab_index.set(index + 1)
                window.activate()
                window.index.set(1)
                return

activate_chrome_tab(tab_title)

(If there are multiple windows with the same tab name it'll focus each one in turn - this is how the original

(Source: Chrome applescript dictionary) (But note appscript is not maintained)

Jason S
  • 13,538
  • 2
  • 37
  • 42
  • Thank you **so** much! Will this also cause the tab to be brought to the foreground? Additionally thanks for the pointer to the Chrome dictionary! – eriophora Aug 14 '14 at 17:49
  • Oh, you want to also focus the window the tab is in. I'll update the answer. – Jason S Aug 14 '14 at 17:54
  • spectacular! thank you so much. While not directly related, do you know of anything that replaces appscript? The script also uses the Quartz library for python, but I've found the reference material to be rather opaque. – eriophora Aug 15 '14 at 23:56
  • I've used `applescript` which involves sending AppleScripts as strings rather than using python objects. It depends on PyObjC, read first: https://pythonhosted.org/pyobjc/install.html – Jason S Aug 16 '14 at 00:09
  • 1
    @eri: Now that 10.10's at last sorted out mess that was 10.9's AppleScript-AppleScriptObjC integration, it's actually fairly painless to call into AppleScript via PyObjC: http://mjtsai.com/blog/2014/10/29/applescript-and-yosemite/#comment-2203684 – foo Nov 23 '14 at 20:27