How to hide a specific window in apple script - applescript

I want to have a script to show and hide a VIM window with a specific file with a keyboard shortcut (will be done over BetterTouchTool). I have everything in the script working, expect the hiding of the window.
I tried to find the opposite of AXRaise, but had no luck to find some documentation regarding this.
toogle-journal.scpt
if application "MacVim" is running then
log "macvim running"
tell application "System Events"
log "tell app system events"
tell application process "MacVim"
log "- tell app process macvim"
if exists (first window whose name contains "journal") then
log "-- window contains journal"
# #todo have to toggle between visible and not visible
if (get frontmost) then
log "true: " & (get frontmost)
# How to hide the window ??
else
log "false: " & (get frontmost)
# set visible to true
# set frontmost to true
perform action "AXRaise" of (first window whose name contains "journal")
end if
else
log "- no window with journal"
do shell script "/Users/foobar/bin/jo > /dev/null 2>&1 &"
end if
end tell
end tell
else
log "no macvim running"
do shell script "/Users/foobar/bin/jo > /dev/null 2>&1 &"
end if

In the context of basic vanilla AppleScript, here are two ways the window of an application can be hidden.
If the miniaturizable property is true, setting its miniaturized property to: true
Set its visible property to: false
Note: When setting the visible property of a window to false, it no longer appears in the list of open windows shown under the Window menu in its UI, and will remain that way until it's reset to true, while the application is still running.
Closing MacVim, normally, with a window still hidden in this manner should cause a Quit without saving? There are modified buffers, if you quit now all changes will be lost. Quit anyway? [Cancel] [Quit] dialog box.
Example AppleScript code:
If MacVim is the active frontmost application then:
To hide by minimizing:
tell application "MacVim" to ¬
set miniaturized of ¬
(first window whose name contains "journal") to true
To unhide when miniaturized is set to: true
tell application "MacVim" to ¬
set miniaturized of ¬
(first window whose name contains "journal") to false
Or:
tell application "MacVim" to ¬
set visible of ¬
(first window whose name contains "journal") to true
To hide by setting visible to: false
tell application "MacVim" to ¬
set visible of ¬
(first window whose name contains "journal") to false
To unhide by setting visible to: true
tell application "MacVim" to ¬
set visible of ¬
(first window whose name contains "journal") to true
If MacVim is not the active frontmost application, then perform any of the above under System Events, e.g.:
tell application "System Events" to ¬
tell application "MacVim" to ¬
set miniaturized of ¬
(first window whose name contains "journal") to true
Note: The example AppleScript code is just that and sans any included error handling does not contain any additional error handling as may be appropriate. The onus is upon the user to add any error handling as may be appropriate, needed or wanted. Have a look at the try statement and error statement in the AppleScript Language Guide. See also, Working with Errors. Additionally, the use of the delay command may be necessary between events where appropriate, e.g. delay 0.5, with the value of the delay set appropriately.

Related

How to "Wait until web page loaded" in Firefox (applescript)?

This code from here works perfect, but doesn't work in Firefox. Why and how to fix it in applescript?
tell application "Google Chrome"
repeat until (loading of tab 1 of window 1 is false)
1 + 1 --just an arbitary line
end repeat
loading of tab 1 of window 1 --this just returns final status
end tell
As Firefox does not contain a specific AppleScript dictionary, e.g. Firefox.sdef file, it is not considered to be AppleScript scriptable in the same way as e.g. Google Chrome, and while it will respond to some of the basic commands, such as activate, quit, etc., it will require UI Scripting to do what you are asking.
The following example AppleScript code requires Firefox version 87 or newer, and setting its accessibility.force_disabled preference to: -1
First, in Firefox, in the Address/Search combo box, type about:config and press enter.
If applicable, click the Accept the Risk and Continue button.
In the Search preference name text box, type accessibility.force_disabled and press enter.
Click the Edit button and change its value to: -1
Click the the Save button.
Here is an example of how I would instruct Firefox to open a new window to a given URL and wait for the page to finish loading.
Example AppleScript code:
set theURL to "https://news.google.com/"
tell application "Firefox" to activate
delay 0.5 -- # Value may need to be adjusted if Firefox is closed.
my clickApplicationMenuCommand("Firefox", "File", "New Window")
delay 0.5
my setURLofFirefoxFrontWindowTo(theURL)
my waitForFirefoxPageToFinishLoading()
say "foobar"
-- # Handler(s) #
to clickApplicationMenuCommand(appName, appMenuName, appMenuCommand)
tell application appName to activate
delay 0.25
tell application "System Events" to ¬
click ¬
menu item appMenuCommand of ¬
menu appMenuName of ¬
menu bar item appMenuName of ¬
menu bar 1 of ¬
application process appName
end clickApplicationMenuCommand
to setURLofFirefoxFrontWindowTo(theURL)
tell application "System Events"
tell application process "Firefox"
set the value of UI element 1 of ¬
combo box 1 of toolbar "Navigation" of ¬
first group of front window to theURL
key code 36 -- # enter key
end tell
end tell
end setURLofFirefoxFrontWindowTo
to waitForFirefoxPageToFinishLoading()
-- # Requires Firefox version 87 or newer.
-- # Requires accessibility.force_disabled set to: -1
tell application "System Events"
tell application process "Firefox"
repeat until exists UI element "Reload" of ¬
toolbar "Navigation" of group 1 of window 1
delay 0.1
end repeat
repeat while (name of UI elements of ¬
toolbar "Navigation" of group 1 of ¬
window 1 whose description is "Reload") ¬
is not {"Reload"}
delay 0.1
end repeat
end tell
end tell
end waitForFirefoxPageToFinishLoading
Notes:
The example AppleScript code, shown above, was tested in Script Editor under macOS Catalina with Language & Region settings in System Preferences set to English (US) — Primary and worked for me without issue1.
1 Assumes necessary and appropriate settings in System Preferences > Security & Privacy > Privacy have been set/addressed as needed.
Tested using Firefox version 91.0 (64-bit).
Note that UI Scripting is very kludgy and is prone to failure, especially as the version of the OS and or application change, or the value of the delay commands are not sufficient. That said however, with Firefox, this as described herein is what it takes.
Note: The example AppleScript code is just that and sans any included error handling does not contain any additional error handling as may be appropriate. The onus is upon the user to add any error handling as may be appropriate, needed or wanted. Have a look at the try statement and error statement in the AppleScript Language Guide. See also, Working with Errors. Additionally, the use of the delay command may be necessary between events where appropriate, e.g. delay 0.5, with the value of the delay set appropriately.

Applescript moving finder window or screen back to first screen

I am writing a script and want to hem in the user(s) in the future from errors. The big one I'm working on right now is that the Choose File command box for Finder or AppleScript (doesn't matter) do not contain the "giving up after" option. So while I can set the timeout to a very large number of seconds (5000 for example), I can't get the box to close and reopen without the Apple Events timing out.
So here is one option I've tried. but the problem I have is that if I swipe to another screen, even if I Activate the finder, it will say that it can't find the window "Choose a File"
Is there a way to get the window to follow the swipe or a command with activate that will bring the finder window to the current screen, even if I'm working in say Safari?
The error occurs when I swipe to another screen; see the error below:
error "System Events got an error: Can’t get window \"Choose a File\" of process \"Finder\"." number -1728 from window "Choose a File" of process "Finder"
Script:
try
with timeout of 5 seconds
tell application "Finder"
set theFilestoChoose to every item of (choose file with prompt "Please select the file(s) you would like to move and rename:" with multiple selections allowed) as list
end tell
end timeout
on error errStr number errorNumber
if errorNumber is -1712 then --timeout error
my closeWindow() --call handler to close window
end if
end try
on closeWindow()
tell application "System Events"
delay 2 -- for observation testing purposes
set frontmost of process "Finder" to true
delay 2 -- for observation testing purposes
click button "Cancel" of window "Choose a File" of process "Finder"
end tell
end closeWindow
You'll have to look into the defaults setting AutoSwoosh = true; defaults write com.apple.Dock workspaces-auto-swoosh -bool YES ; KillAll Dock which makes you go to the active app, if it isn't in the current space, the app itself, (Finder in this case?), shouldn't be assigned to a space.
If that is your basic configuration, then a simple activate before it, should bring you directly to your choose file dialog, if it is in another space.
Here is a fleshed out example of embedding the choose file with tell application (path to frontmost application as text):
tell application (path to frontmost application as text)
set theF to (choose file)
end tell

How to get name of frontmost app with AppleScript and use it to get the filepath

What I try to do:
When I'm in one of my text editors (TextEdit, Byword, FoldingText) I want this AppleScript to display the file path.
I figured asking for the frontmost window app get's me the apps name nice and easily and then I can ask for the POSIX path in the next step.
The Problem:
The script is already 99% there, but I'm missing something. When I try to use the variable of activeApp it doesn't work and I get this error:
Error Number:System Events got an error: Can’t get application {"TextEdit"}.
-1728
Here's the script:
tell application "System Events"
set activeApp to name of application processes whose frontmost is true
--This doesn't work either:
--do shell script "php -r 'echo urldecode(\"" & activeApp & "\");'"
tell application activeApp
set myPath to POSIX path of (get file of front document)
end tell
display dialog myPath
end tell
If I exchange activeApp with "TextEdit" everything works. Help would be appreciated.
Maybe there's something in here that helps: Get process name from application name and vice versa, using Applescript
Either get the path property of a document or use System Events to get value of attribute "AXDocument":
try
tell application (path to frontmost application as text)
(path of document 1) as text
end tell
on error
try
tell application "System Events" to tell (process 1 where frontmost is true)
value of attribute "AXDocument" of window 1
end tell
do shell script "x=" & quoted form of result & "
x=${x/#file:\\/\\/}
x=${x/#localhost} # 10.8 and earlier
printf ${x//%/\\\\x}"
end try
end try
The first method didn't work with Preview, TextMate 2, Sublime Text, or iChm, and the second method didn't work with Acorn. The second method requires access for assistive devices to be enabled.
You are asking for...
set activeApp to name of application processes whose frontmost is true
Notice "processes", that's plural meaning you can get several processes in response so applescript gives you a list of names. Even though only one application is returned it's still in list format. Also see that your error contains {"TextEdit"}. The brackets around the name mean it's a list, so the error is showing you the problem.
You can't pass a list of names to the next line of code. As such you have a couple of choices. 1) you can ask for only 1 process instead of all processes. That will return a string instead of a list. Try this code...
set activeApp to name of first application process whose frontmost is true
2) you can work with the list by using "item 1 of the list". Try this code...
set activeApps to name of application processes whose frontmost is true
set activeApp to item 1 of activeApps
Finally, you shouldn't be telling system events to tell the application. Separate those 2 tell blocks of code. Here's how I would write your code.
tell application "System Events"
set activeApp to name of first application process whose frontmost is true
end tell
try
tell application activeApp
set myPath to POSIX path of (get file of front document)
end tell
tell me
activate
display dialog myPath
end tell
on error theError number errorNumber
tell me
activate
display dialog "There was an error: " & (errorNumber as text) & return & return & theError buttons {"OK"} default button 1 with icon stop
end tell
end try
I can't promise the "get file of front document" code will work. That depends on the application. Not all applications will understand that request. That's why I used a try block. In any case though you can be certain you are addressing the proper application. Good luck.
I've been using this snippet for a while, seems to work for all Cocoa apps (not sure about X11):
set front_app to (path to frontmost application as Unicode text)
tell application front_app
-- Your code here
end tell
None of this seems to work with a compiled AppleScript saved as an application and placed on the Dock. Whenever you run the application, IT is the frontmost, not the application that is showing its front window. That application becomes inactive as my Applescript runs. How do I write an Applescript application that isn't active when it runs?
I may have found a solution to the problem listed above. Just tell the user to reactivate the desired application, and give them time.
tell application "Finder"
activate
say "Click front window of your application"
delay 5
set myapp to get name of first application process whose frontmost is true
-- etc.
-- your code
end tell

Applescript - Bring window to foreground

I have an application with several windows opened at the same time.
I'd like to bring a specific window to foreground (I know its title).
At the moment I'm using a combination of keys to achieve this task but I'd like to try something different since I'm experiencing some problems with this approach.
tell application "System Events"
set frontmost of process "appIT" to true
keystroke "1" using command down
delay 0.2
end tell
This is possible by using the "AXRaise" action, except on certain window (applications that use X11 for example).
Try this.
set theTitle to "some title"
tell application "System Events"
tell process "appIT"
set frontmost to true
perform action "AXRaise" of (windows whose title is theTitle)
end tell
end tell
If your application is scriptable and allows setting the index of a window, you can do the following (based on an answer in How do I make a Safari window active using AppleScript (elegantly)?)
to raiseWindow of theApplicationName for theName
tell the application named theApplicationName
activate
set theWindow to the first item of ¬
(get the windows whose name is theName)
if index of theWindow is not 1 then
set index to 1
set visible to false
set visible to true
end if
end tell
end raiseWindow
The toggling of the visibility is necessary to deal with some weirdness that occurs with switching applications. If you don't toggle the visibility, the window won't be the first when you switch away from and back to the application. Unfortunately, this toggling shrinks the window to the dock then restores it, a very dramatic UI disruption.
Here's another way I've found to deal with the weirdness:
to raiseWindow2 of theApplicationName for theName
tell the application named theApplicationName
activate
set theWindow to the first item of ¬
(get the windows whose name is theName)
if the index of theWindow is not 1 then
set the index of theWindow to 2
tell application "System Events" to ¬
tell application process theApplicationName to ¬
keystroke "`" using command down
end if
end tell
end raiseWindow2
I don't think System Events can change the front window of a process. Of course you can close the front window until the window you want is on top. That's not really a solution though as you probably don't want to close windows. Really though the only way you could achieve this is if the application itself is apple-scriptable and allows you to do this.

AppleScript: Use Lion Fullscreen

There doesn't seem to be any information on this in the official Apple documentation. How do you make an application use Lion's new fullscreen feature via AppleScript?
Not only is it not documented, but the behavior is downright byzantine.
The following applies to Mountain Lion (as of 10.8.1), but I suspect it applies to Lion equally.
The short of it:
You can only examine a fullscreen window's state if it is the active window of the frontmost application. Thus, you must first activate any window you want to examine.
If that window is indeed currently in fullscreen mode but not the active one, activating will take some time - the duration of the transition animation - only after which the window is accessible programmatically.
As long as you're only interested in the active (front) window of the active (frontmost) application, everything's dandy; you're in for pain otherwise.
Below are scripts that do the following:
Indicate if the active window in the active (frontmost) application is in fullscreen mode.
Toggle fullscreen status of the active window in the active application.
Indicate if a specifiable application has any fullscreen windows.
A general-purpose fullscreen-management script that can target a specifiable application; this is much more complex than it should have to be.
Finally, there's some additional background information at the end - great fun.
Note that the scripts below require access for assistive devices to be enabled via System Preferences > Accessibility, or via the following command: tell application "System Events" to set UI elements enabled to true; administrative privileges are required.
Indicates if the active window in the active (frontmost) application is in fullscreen mode
(*
Indicates if the active window of the active application is currently in fullscreen mode.
Fails silently in case of error and returns false.
*)
on isFullScreen()
tell application "System Events"
try
tell front window of (first process whose frontmost is true)
return get value of attribute "AXFullScreen"
end tell
end try
end tell
return false
end isFullScreen
Toggles fullscreen status of the active window in the active application
(*
Toggles fullscreen status of the active window of the active application.
Return value indicates if the window is in fullscreen mode *after* toggling.
Fails silently in case of error, e.g., if the active application doesn't support fullscreen mode, and returns false.
*)
on toggleFullScreen()
set isFullScreenAfter to false
tell application "System Events"
try
tell front window of (first process whose frontmost is true)
set isFullScreen to get value of attribute "AXFullScreen"
set isFullScreenAfter to not isFullScreen
set value of attribute "AXFullScreen" to isFullScreenAfter
end tell
end try
end tell
return isFullScreenAfter
end toggleFullScreen
Indicates if a specifiable application has any fullscreen windows
** Note: This subroutine will only work with AppleScript-enabled applications.**
(*
Determine if the specified, *AppleScript-enabled* application currently has windows in fullscreen mode or not.
Note: Assumes that the application name is the same as the process name.
*)
on hasFullScreenWindows(appName)
-- We compare the count of visible application windows to the count of the application *process'* windows.
-- Since process windows either do not include the fullscreen windows or, if a fullscreen window
-- is active, only report that one window, a discrepancy tells us that there must be at least one fullscreen window.
set countAllWindows to count (windows of application appName whose visible is true)
tell application "System Events" to set countProcessWindows to count windows of process appName
if countAllWindows is not countProcessWindows then
set hasAny to true
else
set hasAny to false
-- The app-window count equals the process-window count.
-- We must investigate one additional case: the app may be currently frontmost and could have
-- a single window that is in fullscreen mode.
tell application "System Events"
set activeProcName to name of first process whose frontmost is true
if activeProcName is appName then
tell process appName
tell front window
set hasAny to get value of attribute "AXFullScreen"
end tell
end tell
end if
end tell
end if
return hasAny
end hasFullScreenWindows
General-purpose fullscreen-management script that can target a specifiable application
** Note: This subroutine will only work with AppleScript-enabled applications.**
(*
Sets the fullscreen status for either the front window or all windows of the specified, *AppleScript-enabled* application.
The 2nd parameter can take the following values:
0 … turn fullscreen OFF
1 … turn fullscreen ON
2 … toggle fullscreen
The 3rd parameter is used to specify whether *all* windows should be targeted.
Example:
my setFullScreen("Safari", 2, false) toggles fullscreen status of Safari's front window.
NOTE:
- ONLY works with AppleScript-enabled applications.
- The targeted application is also activated (also required for technical reasons).
- If you target *all* windows of an application, this subroutine will activate them one by one, which
is required for technical reasons, unfortunately.
This means: Whenever you target *all* windows, expect a lot of visual activity, even when
the fullscreen status needs no changing; activity is prolonged when fullscreen transitions
are involved.
- If the target application has a mix of fullscreen and non-fullscreen windows and the application
is not currently frontmost, the OS considers the first *non*-fullscreen window to
be the front one, even if a fullscreen window was active when the application was
last frontmost.
*)
on setFullScreen(appName, zeroForOffOneForOnTwoForToggle, allWindows)
# Get window list and count.
tell application appName
set wapp_list to windows whose visible is true
set wcount to count of wapp_list
## set wapp_names to name of windows whose visible is true
## log wapp_names
end tell
set MAX_TRIES to 20 # Max. number of attempts to obtain the relevant process window.
set toggle to zeroForOffOneForOnTwoForToggle is 2
set turnOn to false
if not toggle then set turnOn to zeroForOffOneForOnTwoForToggle is 1
if allWindows and wcount > 1 then -- Target *all* the application's windows.
tell application "System Events"
tell process appName
set indexOfTrueFrontWin to -1
set wproc_target to missing value
set wproc_targetName to missing value
-- Loop over application windows:
-- Note that we have 2 extra iterations:
-- Index 0 to determine the index of the true front window, and count + 1 to process the true front window last.
repeat with i from 0 to wcount + 1
## log "iteration " & i
if i ≠ 0 and i = indexOfTrueFrontWin then
## log "ignoring true front win for now: " & i
else
set ok to false
if i ≠ 0 then
set wapp_index to i
if i = wcount + 1 then set wapp_index to indexOfTrueFrontWin
set wapp_target to get item wapp_index of wapp_list
set wapp_targetName to get name of wapp_target -- Note: We get the name up front, as accessing the property below sometimes fails.
end if
repeat with attempt from 1 to MAX_TRIES
## log "looking for #" & i & ": [" & wapp_targetName & "] (" & id of wapp_target & ")"
# NOTE: We MUST activate the application and the specific window in case that window is in fullscreen mode.
# Bizzarrely, without activating both, we would not gain access to that active window's *process* window,
# which we need to examine and change fullscreen status.
if i ≠ 0 then
## log "making front window: " & wapp_targetName
set index of wapp_target to 1 -- Make the window the front (active) one; we try this *repeatedly*, as it can get ignored if a switch from a previous window hasn't completed yet.
end if
set frontmost to true -- Activate the application; we also do this repeatedly in the interest of robustness.
delay 0.2 -- Note: Only when the window at hand is currently in fullscreen mode are several iterations needed - presumably, because switching to that window's space takes time.
try
-- Obtain the same window as a *process* window.
-- Note: This can fail before switching to a fullscreen window is complete.
set wproc_current to front window
-- See if the desired process window is now active.
-- Note that at this point a previous, fullscreen window may still be reported as the active one, so we must
-- test whether the process window just obtained it is the desired one.
-- We test by *name* (window title), as that is the only property that the *application*
-- window class and the *process* window class (directly) share; sadly, only application windows
-- have an 'id' property.
-- (There is potential for making this more robust, though, by also comparing window sizes.)
if i = 0 then
-- We determine the index of the *actual* front window, so we can process it *last*
-- so we return to the same window that was originally active; with fullscreen windows
-- involved, sadly, `front window` is NOT always the true front window.
set indexOfTrueFrontWin to 1
repeat with ndx from 1 to wcount
if name of (item ndx of wapp_list) is name of wproc_current then
set indexOfTrueFrontWin to ndx
exit repeat
end if
end repeat
## log "true front index: " & indexOfTrueFrontWin
set ok to true
exit repeat
else
if (name of wproc_current) is wapp_targetName then
## log "processing: [" & name of wproc_current & "]"
tell wproc_current
set isFullScreen to get value of attribute "AXFullScreen"
if toggle then set turnOn to not isFullScreen
if isFullScreen is not turnOn then
## log "setting fullscreen to: " & turnOn
set value of attribute "AXFullScreen" to turnOn
delay 0.3 -- For good measure; it seems turning fullscreen *on* sometimes fails (you'll hear a pop sound).
else
## log "no change needed"
end if
end tell
set ok to true
exit repeat
else
## log "no match; waiting for '" & wapp_targetName & "', actual: '" & name of wproc_current & "'"
end if
end if
end try
end repeat
if not ok then error "Obtaining process window '" & wapp_targetName & "' of application " & appName & " timed out."
end if
end repeat
end tell
end tell
else if wcount > 0 then -- Target *current* window only (if there is one).
tell application "System Events"
tell process appName
# NOTE: We MUST activate the application in case its active window is in fullscreen mode.
# Bizzarrely, without activating, we would not gain access to that active window's *process* window.
set frontmost to true
set ok to false
repeat with attempt from 1 to MAX_TRIES
delay 0.2 -- Note: Only when the active window is currently in fullscreen mode are several iterations needed - presumably, because switching to that window's space takes time.
try
-- Obtain the same window as a *process* window, as only a process window allows us to examine or
-- change fullscreen status.
tell front window -- Note: This can fail before switching to a fullscreen space is complete.
set isFullScreen to get value of attribute "AXFullScreen"
if toggle then set turnOn to not isFullScreen
if isFullScreen is not turnOn then
set value of attribute "AXFullScreen" to turnOn
end if
end tell
set ok to true
exit repeat
end try
end repeat
if not ok then error "Obtaining active process window of application" & appName & " timed out."
end tell
end tell
end if
end setFullScreen
More background information:
The application windows collection - the one accessible in the context of a tell application ... block - always reports the total number of windows, whether they're in fullscreen mode or not. Unfortunately, such window objects canNOT be used to determine or set fullscreen mode - this must be done via the window objects reported by process objects in the context of the "System Events" application, as only they contain the relevant "AXFullScreen" attribute. It is important to note that the application windows collection - unlike the process windows collection - only works with applications that have AppleScript support.
Unfortunately, the window collection exposed by process objects in the context of the "System Events" application behaves strangely:
○ When an application is not frontmost or one of its NON-fullscreen windows is active, it only contains the NON-fullscreen windows
○ By contrast, when an application is frontmost and one of its fullscreen windows is active, it only ever contains that single fullscreen window, even if other windows (irrespective of whether they're fullscreen or not) exist.
○ Correlating application and process windows is tricky, because only application windows have an 'id' property; the only property the two types share directly is 'name' (i.e., the window title); both types also contains size information, though not in the same format.
○ (Also, process windows never include hidden windows, whereas the application-window collection must be filtered with whose visible is true to exclude hidden windows.)
As a result, if you want to process all windows of a given application, the basic approach is as follows:
○ Activate the application.
○ Loop over all (visible) application window objects.
○ Make each window the front window.
○ Wait for the corresponding process window to become programmatically accessible; this will take quite a while if the window activation involves a fullscreen transition.
○ Examine or change the fullscreen state of the process window (value of attribute "AXFullScreen").
If an application has only full-screen windows, AppleScript can get confused
over what the front window is: what it reports as the front window may not be
the one that is active when you activate the application with AppleScript or Cmd-tab to it.
When using activate to activate an application, a NON-fullscreen window of the target application will be activated, if there is one, even if a fullscreen window of that app was previously active.
You can, however, set the index of a fullscreen window to 1 to activate it.
if you want to toggle between fullscreen and normal mode use this hint
tell application "iTunes"
activate
tell application "System Events" to tell window "iTunes"
of application process "iTunes"
click (every button whose description contains "full screen")
end tell
end tell
You can detect full screen in Lion:
tell application "System Events"
tell process "Safari"
get value of attribute "AXFullScreen" of window 1
end tell
end tell
display dialog result as text
(from http://dougscripts.com/itunes/2011/07/detect-full-screen-mode/).
Another way to do this assuming you have not changed the default keyboard shortcut for "Enter Full Screen" is simply to have System Events invoke that shortcut (⌃⌘F). As with mklement0's wonderfully thorough answer, this requires making the relevant window active.
For instance, to toggle the full-screen state of the frontmost window in Safari, run:
tell application "Safari" to activate
tell application "System Events"
keystroke "f" using {command down, control down}
end tell
(Since the question was about Lion: I'm running macOS Sierra, but unless "Enter Full Screen" and "Exit Full Screen" are not available as menu options in Lion, I expect this would work in Lion as well. If the menu options are available in Lion but are not associated with a keyboard shortcut, it should be possible to add a shortcut under keyboard settings in System Preferences.)

Resources