I just realised this thread is a duplicate of one I started a couple of weeks ago ("Option key down in Yosemite").
With Shane's help there, and Nigel's earlier in this thread, I've produced the following script, which works for me in every app I've tested it on,
tell application "System Events"
set frontapp to POSIX path of (file of process 1 whose frontmost is true) as text
end tell
set oldtds to text item delimiters
set text item delimiters to "/"
set appName to text item -1 of frontapp
set text item delimiters to oldtds
if text item -4 of appName = "." then
set appName to text 1 thru ((offset of "." in appName) - 1) of appName
end if
tell application appName
try
set zoomed of window 1 to not zoomed of window 1
on error
tell application "System Events"
tell application process appName
tell button 2 of window 1
if (action "AXZoomWindow" exists) then
perform action "AXZoomWindow"
else
perform action "AXPress"
end if
end tell
end tell
end tell
end try
end tell
There's a convoluted bit after getting the front process because some apps (like Kindle.app) won't respond to the System Events "tell application process" command if the .app extension isn't removed (others don't seem to mind, like Script Editor). There is a simpler way of doing it, which would allow you to omit all the lines in the script before "tell application appName", which is to just use:
tell application "System Events"
set appName to (name of processes whose frontmost is true) as text
end tell
However, Shane warned me that this might sometimes fail where the app name and process name aren't the same. Hence, I ended up with the above. Works for me.