eriophora eriophora - 4 months ago 56
Python Question

Set active tab in Chrome and bring it to the front

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
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]

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.


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
        for index, tab in enumerate(window.tabs()):
            if title in tab.title():
                window.active_tab_index.set(index + 1)


(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)