Automator Applescript inconsistently handling Google Chrome tabs

applescriptautomatorgoogle-chrome

I want to make an Automator app which closes any open tabs in Google Chrome and loads 3 specific tabs. It should load these 3 tabs regardless of whether Google Chrome was already in use or not.

To accomplish this my app runs the following Applescript:

# Close whatever is already open in Chrome
tell application "Google Chrome"
    close every window
end tell

Next, it uses the "Get Specified URLs" action to understand the list of URLs which I will want to load as tabs. Finally, these URLs are passed into the following Applescript for loading:

# input is the list of url's from the previous task
on run {input, parameters}

    # The below is an applescript loop
    repeat with theURL in input
        tell application "Google Chrome" to open location theURL
    end repeat

    # We must return something so we just return the input
    return input

 end run

When I actually run it, it sometimes works. Other times it does nothing (Chrome is running but has no window or tab loaded) or it opens the 3 new tabs along with whatever tabs were already open when the app was run.

At first I thought perhaps it was being affected by a browser preference which tells Chrome what you would like to have open on startup. I initially had Chrome set to open Gmail. I changed this preference to open only a blank new tab. This did not affect the results (except that when the app otherwise runs successfully now there is an additional blank new tab open, which isn't ideal but I don't care about much).

Best Answer

If an application is what you want, then the following example AppleScript code can be saved as an AppleScript application in Script Editor:

set myURLs to {"https://www.example.com", ¬
    "https://www.apple.com", ¬
    "https://apple.stackexchange.com"}

tell application "Google Chrome"
    activate
    close windows
    set winID to id of (make new window)
    tell window id winID
        set URL of active tab to first item of myURLs
        repeat with i from 2 to (length of myURLs)
            make new tab at end of tabs ¬
                with properties {URL:item i of myURLs}
        end repeat
        set active tab index to 1
    end tell
end tell