MattSh
MattSh

Reputation: 1

AppleScript: Why does this script launch Safari?

This seems simple enough. "if (frontApp = "Safari") then" do the Safari portion. If not, perform the else if portion "else if (frontApp = "Google Chrome") then"

When I have Chrome open and run this script (within an Automator workflow), it runs the Chrome portion fine, then proceeds to open Safari.

What portion of this code is telling Safari to open, and how can I stop that from happening? If only Chrome is open and I'm running it in Chrome, I don't want and don't need Safari to open.

Thanks in advance...

on run {input, parameters}

tell application "System Events" to set frontApp to name of first process whose frontmost is true

if (frontApp = "Safari") then
    using terms from application "Safari"
        tell application frontApp to set currentTabUrl to URL of front document
        tell application frontApp to set currentTabTitle to name of front document
    end using terms from
else if (frontApp = "Google Chrome") then
    using terms from application "Google Chrome"
        tell application frontApp to set currentTabUrl to URL of active tab of front window
        tell application frontApp to set currentTabTitle to title of active tab of front window
    end using terms from
else
    return "You need a supported browser as your frontmost app"
end if

set myInfo to ("MUSIC - " & currentTabUrl & " - " & currentTabTitle)
return myInfo

end run

Upvotes: 0

Views: 340

Answers (2)

McUsr
McUsr

Reputation: 1409

run script is a rather expensive command, so you can optimize the code a bit with this run script instead.

set {currentTabTitle, currentTabUrl} to run script "tell application \"Safari\"
tell current tab of its front window 
return { name, url }
end tell
end tell"

Upvotes: 0

jweaks
jweaks

Reputation: 3792

The "using terms from application 'Safari'" line will launch the app upon first compile or first run when script is opened, at runtime. I recommend putting tell blocks in run script objects, which won't launch unless called:

tell application "System Events" to set frontApp to name of first process whose frontmost is true

if (frontApp = "Safari") then
    set currentTabUrl to run script "tell application \"Safari\" to get URL of front document"
    set currentTabTitle to run script "tell application \"Safari\" to get name of front document"
else if (frontApp = "Google Chrome") then...

Upvotes: 1

Related Questions