Previous version assumed 1P was going to already be unlocked. If it was locked, it just finished. The 1PMini window showing was from the open location
command, which is a background job that runs the search and is unrelated to this script.
Here is an updated script that checks if 1P is locked and if so, waits 10 seconds for you to enter your password. Once it has been unlocked, it copies the search result as desired.
use AppleScript version "2.4" -- Yosemite (10.10) or later
use framework "Foundation"
use scripting additions
on run
set searchTerm to "icloud"
tell application "System Events"
set preClip to (the clipboard) as text
set elements to every UI element whose creator type is "1Ph*"
if elements is {} then
log "1Password Mini is not running"
return false
end if
set mini to (first item of elements)
set miniName to short name of mini
log miniName & " is running as " & name of mini
set isLocked to my isOPMiniLocked(miniName)
open location "x-onepassword-helper://search/" & searchTerm
if isLocked then
if not (my waitForUnlock(miniName, 10)) then
return false
end if
end if
tell its UI element (name of mini)
set frontmost to true
set i to 0
repeat
try
if (focused of text field 1 of window 1) is true then
tell text field 1 of window 1
set value to searchTerm
perform action "AXConfirm"
end tell
delay 1.0
keystroke "c" using {command down, shift down}
delay 0.5
set thePass to (the clipboard) as text
exit repeat
end if
end try
delay 0.1
set i to i + 1
if i > 100 then
return false
end if
end repeat
tell application "App Store" to activate
delay 0.5
keystroke thePass
key code 36
set the clipboard to preClip
end tell
end tell
end run
on isOPMiniLocked(miniName)
tell application "System Events"
tell application process miniName
perform action "AXPress" of menu bar item 1 of menu bar 1
set isLocked to (subrole of text field 1 of window 1 is "AXSecureTextField")
delay 0.1
key code 53 -- Escape key to close 1PMini window
if isLocked then
log "1Password Mini is locked"
return true
end if
log "1Password Mini is unlocked"
return false
end tell
end tell
end isOPMiniLocked
on waitForUnlock(pProcessName, pMaxTimeSec)
local startTime, elapTime, errMsg
set startTime to current application's NSDate's |date|()
log startTime
tell application "System Events"
repeat
set elapTime to (-(round ((startTime's timeIntervalSinceNow()) * 100)) / 100.0)
if (elapTime > pMaxTimeSec) then
set errMsg to "Max Time of " & pMaxTimeSec & " seconds exceeded waiting for " & pProcessName
log errMsg
return false
end if
try
set roleMode to (subrole of text field 1 of window 1) of (application process pProcessName)
if roleMode is "AXSearchField" then
return true
end if
end try
delay 0.1
end repeat
end tell
end waitForUnlock