AppleScript that reads active application name, title and URL
Asked Answered
H

1

6

I need AppleScript that, when lunched from command line, will return three things:

  1. current active application name; ex. "Google Chrome", "Safari", "Steam", "iTunes", "Atom" ect.
  2. current active application title, if there is one
  3. if current active application is a browser, I want the current active tab URL

examples:

I know there are some similar questions w. answers here on stackoverflow, but I am not able to pice them together to make all of this work. Would appreciate help much.

Hackery answered 9/2, 2018 at 19:52 Comment(2)
Relevant: Time Sink is commercial software for periodically recording the current application and window title and analyzing the results. It doesn’t track the current URL, though.Returnable
@RoryO'Kane yeah, I've been using Time Sink for almost a year. It's.. Well, it's alright, especially given I've paid $5 for it. With "URL in tab" plugin and some work setting up filters, it gets job done, if you want to track your focus.Hackery
E
6

I wanted to make a script that does exactly this running in the background so that I can better keep track of my time. Here's what I came up with:

tell application "System Events"
    set frontmostProcess to first process where it is frontmost
    set appName to name of frontmostProcess
end tell
tell application appName
    set windowName to the name of the front window
end tell
if appName is equal to "Safari" then
    tell application "Safari"
        set theURL to the URL of the current tab of the front window
    end tell
else if appName is equal to "Google Chrome" then
    tell application "Google Chrome"
        set theURL to the URL of the active tab of the front window
    end tell
else
    set theURL to ""
end if

return (appName, windowName, theURL)

Credit goes to https://apple.stackexchange.com/a/171738 for getting me on the right track.

Experienced answered 17/8, 2018 at 0:7 Comment(1)
This script will fail if the application is not scriptable: tell application AppName to set windowName to the name of the front window won't work for non-scriptable apps.Gratuity

© 2022 - 2024 — McMap. All rights reserved.