Applescript: Open current Safari tab in Chrome (Troubleshoot of working script)

alfredapplescriptgoogle-chromesafari

So, I decided a while ago to run a Flash-free install of Safari. It's been really great, Safari seems much more stable overall and I barely miss it.

But every once in a while I stumble upon a site that requires flash (mostly YouTube videos, which I thought wouldn't be a problem given that Google was supposed to be switching everything over to HTML5), so for those cases I have an Appescript that runs when triggered through an Alfred Workflow (with a hotkey). The script is as such:

tell application "Safari"

    set theURL to URL of current tab of window 1

end tell

tell application "Google Chrome"

    if windows ≠ {} then
        make new tab at the end of window 1 with properties {URL:theURL}
    else
        make new window
        set URL of active tab to theURL
    end if
    activate

end tell

tell application "Safari"

    close current tab of window 1

end tell

This usually runs perfectly, but I run into a weird problem whenever Chrome doesn't have an open window in the background. In these cases, Chrome will open a new (blank) window, and the script will stop right there. The third Tell statement,

 tell application "Safari"

    close current tab of window 1

end tell

Will never run, leaving me with an open chrome window and an open safari window as well. It is only after I press the hotkey a second time, after the Chrome window is already open, that the Script will run it's course and open the page in chrome/close the tab in safari.

Any ideas? I'm really confused by the fact the third tell statement won't run at all. If the Chrome window opened up blank but the safari tab still closed I would guess it was a simple error in the if/else statement, but the fact that the script seems to terminate is really stumping me on this one.

Best Answer

Just because Safari and Chrome are running, doesn't mean that they have a window open. You can either test for open windows as Mark points out or simply issue the reopen command which opens a new window if one does not exist.

tell application "Google Chrome"
    if not (exists window 1) then reopen
    -- insert your code 
end tell

tell application "Safari"
    if not (exists document 1) then reopen
    -- insert your code 
end tell

EDIT

tell application "Safari"
    if not (exists document 1) then return
    set theURL to URL of current tab of window 1
    close current tab of window 1
end tell

tell application "Google Chrome"
    if not (exists window 1) then reopen
    set URL of active tab of window 1 to theURL
end tell