The application of the frontmost window

How to know what is the application of the frontmost window?

Something like:

if (frontmost window is Pages) then
set program to “pages”
else if (frontmost window is Numbers) then
set program to “numbers”
else
set program to “other”
end if

tell application "System Events"
	get name of first process whose frontmost is true
end tell

Ok, I get the answer “Script Editor” And if I export this as a program I will get that program as the frontmost. So, I suppose I should ask what is the second window?

In fact, I only need to activate the last window from Pages or Numbers (That is the last active window apart from the script editor or the program generated by the script editor)

I’m not certain if I understand what’s required but you can give the following a try:

tell application "System Events" to tell process "Numbers"
	set frontmost to true
	perform action "AXRaise" of the last window
end tell

I try to know if the frontmost window is Pages, Numbers, or something else

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

if frontmostName is "Pages" then
--do some stuff
else if frontmostName is "Numbers" then
--do some other stuff
else
--do nothing or something else
end if 

That is similar to Otto answer. This is useful. Thank you. But as I said to him, the problem is that the frontmost is the Script Editor

Something like this. Hide the current application.


set currentApp to name of current application

tell application "System Events"
	set visible of process currentApp to false
	set frontAppName to name of first process whose frontmost is true
end tell

The frontmost app will vary, depending on how your script is run and its format.

FWIW, if you run Otto’s script from the general script menu, it will do what you want (at least it does in Sierra).

tell application "System Events"
	set xy to name of first process whose frontmost is true
end tell
display dialog xy

As an aside, if pages/numbers are the second app (when script editor or a saved script is the first), you could probably ask for a list of open apps with the desired app having an index of 2, and then get its name. Haven’t tested this so maybe I’m out on a limb.

I see. Okay, that happens when running the script from within Script Editor, because Script Editor is frontmost at that time.

If you save the script in the Scripts folder and run it from the Script menu or run it from an applet, then it will tell you which Application frontmost at the time.