1
votes

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.

2
Regarding the code indention from the help: You can also select text and press CTRL+K to toggle indenting as code. - vadian
They need to make that more clear on the webpage. - bobsmith76
Allow me to give you the standard advice to newcomers: If an answer solves your problem, please accept it by clicking the large check mark (✓) next to it and optionally also up-vote it (up-voting requires 15 or more reputation points). If you found other answers helpful, up-vote them. Accepting (for which you'll gain 2 reputation points) and up-voting helps future readers. Please see the relevant help-center article. If your question isn't fully answered yet, please provide feedback or self-answer. - mklement0

2 Answers

3
votes

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 duplicates and applications whose process names differ.

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).

2
votes

Even better than both other approaches is using the bundle identifier which is a unique key.

tell application "System Events"
    set frontAppID to bundle identifier of first process whose frontmost is true
end tell

-- Sample code... can be anything else
activate application "Finder"
delay 3
-- End of sample code

activate application id frontAppID