如何编写通用AppleScript获取指定macOS应用支持打开的文件扩展名
原脚本失效原因
- 只提取每个文档类型下的第一个扩展名,遗漏同类型关联的其他扩展名
- 未处理部分应用使用
LSItemContentTypes(UTI统一类型标识符)声明支持格式的情况,这类应用不会直接在CFBundleTypeExtensions下列出扩展名 - 没有做字段存在性校验,遇到无对应key的条目会直接报错
修正后通用脚本
use AppleScript version "2.4" use scripting additions use framework "Foundation" -- 选择应用并获取路径 set applicationPosixPath to POSIX path of (path to (choose application)) set theURL to current application's |NSURL|'s fileURLWithPath:applicationPosixPath set theBundle to current application's NSBundle's bundleWithURL:theURL set CFBundleDocumentTypes to (theBundle's infoDictionary()'s objectForKey:"CFBundleDocumentTypes") as list set theExtensions to {} set workspace to current application's NSWorkspace's sharedWorkspace() repeat with anItem in CFBundleDocumentTypes -- 处理直接声明CFBundleTypeExtensions的情况 if (anItem's objectForKey:"CFBundleTypeExtensions") is not missing value then set extList to (anItem's objectForKey:"CFBundleTypeExtensions") as list repeat with ext in extList if ext is not in theExtensions then set end of theExtensions to ext as text end repeat end if -- 处理通过UTI声明支持格式的情况,转换为对应扩展名 if (anItem's objectForKey:"LSItemContentTypes") is not missing value then set utiList to (anItem's objectForKey:"LSItemContentTypes") as list repeat with uti in utiList set ext to (workspace's preferredFilenameExtensionForType:uti) if ext is not missing value and (ext as text) is not in theExtensions then set end of theExtensions to ext as text end if end repeat end if end repeat return theExtensions
优化说明
- 新增字段存在性校验,避免无对应key时直接报错
- 遍历每个文档类型下所有的扩展名,而非仅取第一个
- 新增UTI转扩展名逻辑,兼容通过UTI声明支持格式的应用,解决Finder、Handbrake这类应用读取失败的问题
- 新增去重逻辑,避免同一个扩展名被多次添加
内容的提问来源于stack exchange,提问作者Robert Kniazidis
相关产品推荐
相关产品推荐

