通过URL协议运行AppleScript时无法激活指定应用
问题原因
当通过URL协议触发AppleScript应用时,系统只会执行on open location处理程序内的代码,你写在这个处理程序之外的进程检查和应用激活逻辑根本不会被执行。这就是为什么双击或终端运行时功能正常(此时会执行整个脚本),但URL触发时仅完成了写入文件的操作。
修复方案
把所有逻辑整合到on open location处理程序中,同时改用AppleScript原生方式检查并激活应用(比do shell script更可靠,也能避免权限相关问题):
on open location this_URL -- 1. 将URL写入指定文件 set userHomePath to POSIX path of (path to home folder) set argFile to userHomePath & "Downloads/uriNotifier.txt" do shell script "echo " & quoted form of this_URL & " > " & quoted form of argFile -- 2. 检查目标应用是否运行并激活 tell application "System Events" set isRunning to exists process whose bundle identifier is "my.App.ID" end tell if isRunning then tell application id "my.App.ID" to activate end if end open location
额外优化建议
- 移除脚本开头的
#!/bin/bash,这是Shell脚本的标识,AppleScript不需要,保留可能引发混淆。 - 确保你的AppleScript应用已获取辅助功能权限(系统设置 > 隐私与安全性 > 辅助功能),否则
System Events可能无法正确检测进程状态。 - 若坚持使用
open -b命令,也必须将其放到on open location代码块内部,但原生AppleScript调用的兼容性和稳定性更优。
内容的提问来源于stack exchange,提问作者Santanu Karar
相关产品推荐
相关产品推荐

