如何让Shell脚本调用的osascript对话框归属父AppleScript应用?
让Bash脚本中调用的osascript对话框归属到父AppleScript应用
核心问题原因
你当前用osascript -e 'tell me to display dialog...'时,tell me指向的是单独启动的osascript进程本身——这是一个无界面的系统级进程,所以弹出的对话框不会关联到你的AppleScript应用,点击也不会切换应用前台。
解决方案:传递父应用标识给脚本
最可靠的方式是直接从AppleScript应用中把自身的Bundle ID传递给script.sh,再在脚本中指定以此ID为目标调用对话框。
步骤1:修改AppleScript代码,传递Bundle ID
在你的AppleScript应用里,调用script.sh时附加自身的Bundle ID作为参数:
set myBundleID to id of current application set scriptPath to POSIX path of (path to resource "script.sh") do shell script quoted form of scriptPath & " " & quoted form of myBundleID
步骤2:修改script.sh,使用传递的Bundle ID
在script.sh中接收参数,并用该Bundle ID指定对话框所属应用:
# 接收AppleScript传递的父应用Bundle ID PARENT_BUNDLE_ID="$1" # 调用osascript时,明确指定归属的应用 osascript -e "tell application id \"$PARENT_BUNDLE_ID\" to button returned of (display dialog \"blabla.Do you want blabla.\" buttons {\"yes\", \"no\"})"
备选方案:自动查找父应用(不推荐)
如果无法修改AppleScript传递参数,可以通过父进程链查找AppleScript应用的Bundle ID,但这种方式易受进程层级变化影响:
# 从当前脚本的父进程开始,向上遍历找到AppleScript应用进程 APP_PID=$PPID while true; do PROC_NAME=$(ps -p $APP_PID -o comm=) # 替换成你的AppleScript应用名称,比如"MyCustomApp" if [[ $PROC_NAME == "MyCustomApp" || $PROC_NAME == "Script Editor" ]]; then break fi APP_PID=$(ps -p $APP_PID -o ppid=) [[ $APP_PID -eq 1 ]] && { echo "未找到父应用"; exit 1; } done # 获取应用的Bundle ID PARENT_BUNDLE_ID=$(mdls -name kMDItemCFBundleIdentifier -raw "$(ps -p $APP_PID -o path=)") # 弹出归属到父应用的对话框 osascript -e "tell application id \"$PARENT_BUNDLE_ID\" to button returned of (display dialog \"blabla.Do you want blabla.\" buttons {\"yes\", \"no\"})"
这样修改后,对话框会归属到你的AppleScript应用,点击时会自动切换该应用到前台。
内容的提问来源于stack exchange,提问作者Greg
相关产品推荐
相关产品推荐

