I need to execute some keystrokes by applescript (for example, cmd + t
to create a new tab) in some app (for example, safari browser). So, I’ve written a code:
tell application "Safari" to activate
tell application "Safari"
set wList to every window whose visible is true
repeat with app_window in wList
log app_window
set index of app_window to 1
tell application "System Events"
keystroke "t" using {command down}
end tell
delay (1)
end repeat
end tell
I expect this code to open a new tab in each opened safari window. But actually, this code just opens n
new tabs in the first active safari window, where n
– is count of opened safari windows. It seems like I have a problem with focus changing in this line:
set index of app_window to 1
So, how to change focus correctly to execute keystrokes in each window?
UPD
Interesting thing – this code works correctly with Finder app (just replace Safari -> Finder), but it does not work with safari and ios simulators (Xcode)
UPD
Also, it doesn’t work with Google Chrome – I’m getting the same behavior.
2
Answers
If you want to add a new
tab
to all the windows in Safari, then here is how it can be done:Example AppleScript code:
Notes:
You can change
at end of tabs
to a different location, i.e,:For example:
at beginning of tabs
Update to address comment:
Example AppleScript code:
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.You can’t control indexes of windows directly, because property index is read/only. But you can do it with help of Safari.app:
NOTE: you can use visible property instead of miniaturized property (no need delay):