Switch between Google Chrome Tabs using AppleScript

I was hoping that the following code would do the job, but no cigar:

--Only the window is brought into focus
tell application "Google Chrome"
    activate tab 1 of window 1
end tell

Solution 1:

Google Chrome is, in fact, scriptable.

tell application "Google Chrome" to set active tab index of first window to 3

Works like a charm for version 10.0.648.204.


While it would be nice to do something like the following:

tell application "Google Chrome" to set active tab of first window 
    to first tab of the first window whose title is "Super User"

It's not possible, since active tab is a read-only property. You'd need to loop over all a window's tabs to find the index of the one you want by querying each tab's title, and then set the active tab index:

tell application "Google Chrome"
    set i to 0
    repeat with t in (tabs of (first window whose index is 1))
        set i to i + 1
        if title of t is "Super User" then
            set (active tab index of (first window whose index is 1)) to i
        end if
    end repeat
end tell

Solution 2:

I just finished this amazing script, which required a lot of googling and guessing, but it works.

tell application "Google Chrome"
    activate
    repeat with w in (windows)
        set j to 0
        repeat with t in (tabs of w)
            set j to j + 1
            if title of t contains "Workflowy" then
                set (active tab index of w) to j
                set index of w to 1
                tell application "System Events" to tell process "Google Chrome"
                    perform action "AXRaise" of window 1 -- `set index` doesn't always raise the window
                end tell
                return
            end if
        end repeat
    end repeat
end tell

The do shell script is from here: it gets the Window to accept keystrokes.

You can use FastScripts to make this work (and there are many other methods, too)

Solution 3:

I was trying to write a script to pause and play Netflix, and the code provided above was a good framework for searching through the tabs. "whose index is 1" kept throwing compiler errors on my Mac Mini 10.8.3, so, based on code from http://en.blog.guylhem.net/post/9835498027/google-chrome-next-tab-in-applescript , I just removed the reference entirely (which worked for my purposes)

The script basically activates the browser window, goes through tabs until it finds one titled "Netflix", and sends it key code 49 (spacebar).

tell application "Google Chrome"
    activate
    set i to 0
    repeat with t in (tabs of (first window))
        set i to i + 1
        if title of t is "Netflix" then
            set (active tab index of (first window)) to i
        end if
    end repeat
    tell application "System Events" to key code 49
end tell