When I run the following script from the macOS Script Menu, the resulting NSAlert appears but doesn’t have focus. How can I ensure that it gets focus without me having to click on it?
use AppleScript version "2.4"
use scripting additions
use framework "Foundation"
use framework "AppKit"
property NSAlert : a reference to current application's NSAlert
tell NSAlert's alloc()'s init()
set theAlert to it
its setMessageText:"The quick brown fox jumps over the dog"
its setInformativeText:"Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt."
its runModal()
end tell
Should I be telling a process (ScriptMonitor? osascript?) to activate or become frontmost, or am I just out of luck in this scenario? Any advice would be much appreciated.
use AppleScript
use scripting additions
use framework “Foundation”
use framework “AppKit”
property NSAlert : a reference to current application’s NSAlert
my performSelectorOnMainThread:“dispAlert:” withObject:(missing value) waitUntilDone:true
on dispAlert:paramObj
–Move to frontmost (By edama2)
current application’s NSApplication’s sharedApplication()'s setActivationPolicy:(current application’s NSApplicationActivationPolicyRegular)
current application’s NSApp’s activateIgnoringOtherApps:(true)
tell NSAlert’s alloc()'s init()
set theAlert to it
its setMessageText:“The quick brown fox jumps over the dog”
its setInformativeText:“Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt.”
its runModal()
end tell
end dispAlert:
Just for what it’s worth, if you use my FastScripts utility instead of the Apple Script Menu, it strives to streamline situations like this so that things are more usable, without any extra effort in the script. In general when a script causes a new window to appear, FastScripts ensures that the process that is running the script becomes frontmost.
FastScripts also requires the changes Piyomaru suggested, to run the alert on the main thread, but if you run the script in FastScripts you wouldn’t have to do the work of requesting that the current application activates.
Sorry for the shameless plug but I’ll also add that if you are just using Apple’s script menu for its menu selection functionality, that’s completely free in FastScripts, and in my opinion it does a better job by covering situations like this more gracefully.