Using AppleScript to choose a file in Safari - macos

I am trying to write some automation code (primarily in Ruby Selenium). At some point, a file chooser is opened in Safari so that the user can select a file for upload. Selenium cannot handle this, but I think AppleScript should be able to. I am new to AppleScript and haven't been able to find any boilerplate code of someone automating a file chooser dialog. I'm reading through the AppleScript docs, but any ideas would be most helpful.

Some more searching and I found a great answer here: Applescript file dialog with UI scripting
Here's what I ended up using:
on run argv
tell application "Safari"
activate
-- Usage check
set argc to count argv
if argc is not greater than 0 then
return "Usage: SafariFileChooser file_name [window_name]"
end if
-- The file we will choose to open
set file_name to item 1 of argv
-- Flip to the named window, if specified
if argc is equal to 2 then
set window_name to item 2 of argv
set flip_count to index of window window_name
repeat (flip_count - 1) times
activate
tell application "System Events" to keystroke "`" using command down
end repeat
end if
-- Interact with the dialog using System Events (thanks mcgrailm)
tell front window
activate
tell application "System Events"
keystroke "g" using {shift down, command down}
keystroke file_name
delay 1
keystroke return
delay 1
keystroke return
end tell
end tell
end tell
return 0
end run

Another option I just discovered is to specify the directory using the command-line:
do shell script "defaults write com.apple.Safari NSNavLastRootDirectory /path/to/directory"
This way you can do slightly less in UI scripting. Run this command before you open the file chooser, and it will put you into the directory specified. Include all the files you need in this directory, and you can just script command+a to select them all, and return.

Related

Applescript does not run user command

I need the applescript to run tabset test command to change the name of the current tab of iTerm.
-- Launch iTerm and log into multiple servers using SSH
tell application "iTerm"
activate
create window with default profile
set newWindow to (create window with default profile)
set Servers to paragraphs of (do shell script "/bin/cat $HOME/serverlist")
repeat with nextLine in Servers
if length of nextLine is greater than 0 then
tell current window
create tab with default profile
tell current session of newWindow
do shell script "export PATH='/usr/local/bin:$PATH'; tabset test "
end tell
end tell
end if
end repeat
tell first tab of current window
close
end tell
tell second window
close
end tell
end tell
The problem is tabset test does not work, and there is no any error prompted.
The tabset command could be installed via npm install -g iterm2-tab-set
Ted Wrigley is right. I should use iTerm's write command to type the text into the window.

Applescript - save argument to text file

I need to write a simple applescript that will be opened with an argument. That argument will be a file path. I need it to save this file path to a text file. I want to avoid using shell script.
I'm finding this surprisingly difficult, despite having done it in .sh and .bat already
Thanks very much!
Adam
//// the current code which is not working is below. the code begins with "on run" and ends with "end run" but for some reason this isn't being highlighted as code
on run argv
set this_PATH to (POSIX file argv)
tell application "TextEdit"
activate
make new document
set text of document 1 to this_PATH as text
save document 1 in "/Users/adamparkinson/Desktop/date.txt"
end tell
end run
I made this work:
#!/usr/bin/osascript
on run argv
tell application "TextEdit"
activate
make new document
tell document 1
set its text to (item 1 of argv as text)
save in posix file (item 1 of argv as text )
end tell
end tell
end run
I called it like this:
./SavePath.sh /Users/Me/Desktop/junk/Newstuff.txt (Of course I used chmod u+x SavePath.sh to make it executable.)
If this works for you, then please check of my answer as answered. :)
with applescript it is very easy to create application Drag and Drop without any script shell below a version Drag and Drop of your script
on open draggedItems
set this_PATH to quoted form of POSIX path of draggedItems
repeat with currentItem in draggedItems
tell application "TextEdit"
activate
set doc to open POSIX file "/Users/adamparkinson/Desktop/date.txt"
make new word at end of text of doc with data (this_PATH as text) & return
end tell
end repeat
end open

Run emacs using applescript and open file

What I would like to do is have an automator script open a file in emacs when I drag a file onto it, and bring terminal to the front.
Right now, when I try to do this with input set to ~/Desktop/test.txt, it either opens up the main page, or it ends up with ~/Desktop/testtxt. Am I doing this wrong? Is there a better way to do this?
This is what I have right now:
set thePath to POSIX path of input
tell application "Terminal" to do script "emacs"
tell application "System Events"
tell process "Terminal"
activate
delay 2
keystroke "x" using control down
delay 1
keystroke "f" using control down
delay 1
keystroke thePath
delay 1
keystroke return
delay 1
end tell
end tell
return input
end run
Use the file path as an argument to emacs
on run {input}
tell application "Terminal"
repeat with i in input
do script "emacs " & quoted form of POSIX path of i
end repeat
activate
end tell
return input
end run

Save ppt as pdf via applescript with Preview.app

I write script to convert xls to pdf with applescript.
Here is my code:
set the_file to (choose file)
tell application "Preview"
activate
open the_file
end tell
tell application "System Events"
tell process "Preview"
keystroke "p" with command down
tell front window
UI elements
end tell
end tell
end tell
When i run script, i have error in
keystroke "p" with command down
whats wrong?
You need the keyword using instead of the keyword with. So, the erroneous line should read:
keystroke "p" using command down

Opening multiple windows with Applescript

I am trying to write an Applescript to open three VLC windows in different screen positions. The script opens three instances of VLC but has them one on top of the other (using the position for window 1). Help with the code appreciated:
do shell script "open -n /Applications/Video/VLC.app"
tell application "System Events"
activate
set bounds of first window of application "VLC" to {13, 36, 790, 519}
end tell
do shell script "open -n /Applications/Video/VLC.app"
tell application "System Events"
activate
set bounds of second window of application "VLC" to {13, 544, 790, 1027}
end tell
do shell script "open -n /Applications/Video/VLC.app"
tell application "System Events"
activate
set bounds of third window of application "VLC" to {13, 1043, 790, 1526}
end tell
#khagler's comment provides the right pointer: the VLC instances must be distinguished by their PIDs (process IDs; called unix id in AppleScript) in the System Events context.
The code below should do what you want, arrived at after much toil and trouble -- par for the [AppleScript obstacle] course. One obstacle was that the VLC instances' main windows do not get created right away.
The comments provide more details.
Note that because user-interface elements are programmatically manipulated, the application running your script must be granted assistive access for security reasons.
Note that I'm starting the instances with do shell script "open -na VLC.app", relying on the location of the app being known to Launch services (should that not work for some reason, revert to your method of specifying the full path).
# Specify the desired window bounds.
# !! In the "System Events" context, windows do not
# !! have `bounds` properties, but separate `position` and
# !! `size` properties.
set WIN_POSITIONS to {{13, 36}, {13, 544}, {13, 1043}}
set WIN_SIZES to {{790, 519}, {790, 519}, {790, 519}}
# Launch the VLC instances.
repeat with i from 1 to count of WIN_POSITIONS
do shell script "open -na VLC.app"
end repeat
# Note:
# Instance-specific manipulation must
# be performed in the "System Events" context, because
# we must distinguish the VLC instances by their
# PIDs (process IDs; called `unix id` in AppleScript).
tell application "System Events"
# Get the PIDs (process IDs) of all VLC instances.
set vlcPids to get the unix id of every process whose name is "VLC"
# Loop over all instance PIDs.
# !! It is imperative to *continue* to use object specifiers
# !! with *filters based on the PID* so as to ensure that the
# !! individual instances are targeted.
# !! Attempting to store references to these instances in
# !! variables fails subtly, as evidenced by the "Events"
# !! tab in AppleScript editor later showing the non-specific
# !! process "VLC" of application "System Events" specifiers.
set winNdx to 1
repeat with vlcPid in vlcPids
# WAIT for each instance to create its main window, wich
# sadly, is not available right away.
# Once created, position it.
set haveWin to false
tell (first process whose unix id is vlcPid)
repeat with i from 1 to 25 # times out after 25 * .2 == 5 secs.
if (count of windows of it) > 0 then
set haveWin to true
tell front window of it
# !! In the "System Events" context, windows do not
# !! have `bounds` properties, but separate `position` and
# !! `size` properties.
set position to item winNdx of WIN_POSITIONS
set size to item winNdx of WIN_SIZES
end tell
exit repeat
end if
delay 0.2 # no window yet; sleep some and try again
end repeat
end tell
if not haveWin then error "VLC instance " & vlcPid & " unexpectedly did not create a window within the timeout period."
set winNdx to winNdx + 1
end repeat
end tell
How to make this work with Finder:
Targeting Finder changes the approach for two reasons:
there's only one Finder instance.
you cannot open multiple windows with open -na Finder.app; thankfully, this answer shows how to do it (see the comments there for quirks).
Note that the following blindly opens additional Finder windows.
set WIN_POSITIONS to {{13, 36}, {13, 544}, {13, 1043}}
set WIN_SIZES to {{790, 519}, {790, 519}, {790, 519}}
# Sample target locations for the Finder windows.
# Note the use of the "System Events" context to faciliate use of
# POSIX-style *input* paths; note, however, that the paths are
# *stored* as HFS paths so that Finder accepts them.
tell application "System Events"
set WIN_TARGETS to {¬
path of desktop folder, ¬
path of folder "~/Downloads", ¬
path of folder "/Library/Audio"}
end tell
set winCount to count of WIN_POSITIONS
# Launch the Finder windows.
tell application "Finder"
# Create the windows in reverse orders.
repeat with i from winCount to 1 by -1
set newWin to make new Finder window
set target of newWin to item i of WIN_TARGETS
end repeat
end tell
tell application "System Events"
set i to 1
repeat with i from 1 to winCount
tell window i of application process "Finder"
# !! In the "System Events" context, windows do not
# !! have `bounds` properties, but separate `position` and
# !! `size` properties.
set position to item i of WIN_POSITIONS
set size to item i of WIN_SIZES
end tell
end repeat
end tell
After scouring the internet and much trial & error I have found this works well providing you allow the AppleScript Editor (or automator or your own app, whichever you are using) to control your computer under System Preferences > Security & Privacy > Privacy > Accessibility (OS X 10.9 Mavericks). The first time you run the script/app you'll be prompted to change the setting. After granting access, the second time you run the script/app the windows will be re-positioned.
do shell script "open -n /Applications/VLC.app /path/to/first/file" --edit path
do shell script "open -n /Applications/VLC.app /path/to/second/file" --edit path
delay 3 --wait 3s for VLC to open files, increase if necessary
tell application "System Events"
set pidList to the unix id of (every process whose name contains "VLC")
tell (first process whose unix id is item 1 of pidList)
set the position of the front window to {0, 22} --edit {x,y}
end tell
tell (first process whose unix id is item 2 of pidList)
set the position of the front window to {640, 22} --edit {x,y}
end tell
end tell
It's not as clever as mklement0's answer but, as someone who is new to AppleScript, I could understand what's going on.

Resources