Set active tab in Chrome and bring it to the front

2.2k Views Asked by At

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.

1

There are 1 best solutions below

5
On BEST ANSWER

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)