Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

set application to frontmost in applescript

Tags:

applescript

I'm trying to find out what the frontmost application x is, run a script, then set x to the frontmost application using applescript.

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

[code here]

tell application "System Events"
set frontmost of process whose name is apptemp to true
end tell

Although this code does not return any bugs it does not work. I've also tried this code

tell application "System Events"
set apptemp to application "Google Chrome"
set frontmost of process "Google Chrome" to true
end tell

But again, although there are no bugs it will not work.

Also, someone please tell the admin to make it easier to display code. I have the most difficult time displaying code on this website. I have to indent four spaces for each line of code, that's insane.

like image 783
bobsmith76 Avatar asked Feb 02 '26 16:02

bobsmith76


1 Answers

A robust way to handle this is to use path to frontmost application as follows:

# Save which application is frontmost (active),
# as an absolute, HFS-style path string pointing to the application bundle.
set frontmostAppPath to (path to frontmost application) as text

# Activate and work with another application.
activate application "Reminders"
delay 2

# Make the previously frontmost (active) application frontmost again.
activate application frontmostAppPath

Using the application's specific path ensures that the very same application is reactivated, irrespective of potential duplicates in different folders; also, this method is not affected by applications whose process name differs from the application name. However, should there be multiple instances of the application running, it isn't necessarily the original instance that is reactivated.

Note: It's tempting to want to save and restore the object reference frontmost application directly, but that doesn't actually work: inexplicably, such a saved reference is treated the same as the current application (the one running the code).

like image 54
mklement0 Avatar answered Feb 05 '26 08:02

mklement0