AppleScript获取活跃应用文件路径失败问题求助
AppleScript获取活跃应用文档路径问题解决
你的组合脚本失效的核心原因是AppleScript的编译机制:当使用变量引用应用(tell application activeApp)时,编译器无法提前识别目标应用的AppleScript术语(比如path of front document),导致运行时术语解析失败,mypath变量未被正确赋值,最终对话框无内容。
修正后的基础脚本
tell application "System Events" set activeApp to name of first application process whose frontmost is true end tell -- 动态生成并执行针对目标应用的脚本,避免编译时术语解析问题 set getPathScript to "tell application \"" & activeApp & "\" to get path of front document" set mypath to run script getPathScript display dialog mypath
带异常处理的版本(兼容更多应用)
考虑到部分应用不支持front document或path属性,添加异常处理避免脚本崩溃:
tell application "System Events" set activeApp to name of first application process whose frontmost is true end tell try set getPathScript to "tell application \"" & activeApp & "\" to get path of front document" set mypath to run script getPathScript display dialog mypath on error errMsg display dialog "无法获取文件路径:" & errMsg buttons {"确定"} default button 1 end try
原理说明
通过run script动态生成脚本字符串,让AppleScript在运行时加载目标应用的AppleScript字典,从而正确解析path of front document这类应用专属术语,解决变量引用应用时的编译限制问题。
内容的提问来源于stack exchange,提问作者Fred Lager
相关产品推荐
相关产品推荐

