如何用AppleScript关闭弹窗?PDF转TXT的AppleScript代码技术问询
解决AppleScript批量转换PDF时关闭Adobe Acrobat弹窗的问题
我之前在做类似的PDF批量转TXT脚本时,也碰到过Acrobat弹出各种确认、警告弹窗的情况,下面给你几个实用的解决思路和代码修改方案:
方案1:用System Events自动识别并点击弹窗按钮
这是最直接的方法,通过AppleScript调用System Events来监测弹窗,自动点击确认/取消按钮。你可以把这段代码嵌入到你的循环里,处理每个文件转换时的弹窗:
set homeFolder to path to home folder as text set sourceFolder to homeFolder & "pdffolder:" set txtFolder to homeFolder & "txtfolder:" tell application "Finder" set fileSet to get every file of folder sourceFolder whose name ends with ".pdf" -- 只筛选PDF文件,避免非PDF文件触发错误 end tell activate application "Adobe Acrobat Pro" -- 先尝试关闭Acrobat的默认警报提示 tell application "Adobe Acrobat Pro" set display alerts to false end tell repeat with aFile in fileSet set currentFile to aFile as text set currentFileName to name of aFile set outFile to txtFolder & text 1 thru -5 of currentFileName & ".txt" -- 打开PDF并执行转换(补全你原有的转换逻辑) tell application "Adobe Acrobat Pro" open currentFile export active document to file outFile as text close active document saving no end tell -- 监测并关闭可能出现的弹窗 tell application "System Events" -- 替换成你实际遇到的弹窗标题,比如中文环境的"Adobe Acrobat"或"警告" if exists window "Adobe Acrobat" of application process "Adobe Acrobat" then try click button "确定" of window "Adobe Acrobat" of application process "Adobe Acrobat" end try end if -- 可根据实际弹窗添加更多判断 if exists window "警告" of application process "Adobe Acrobat" then try click button "确定" of window "警告" of application process "Adobe Acrobat" end try end if end tell end repeat
方案2:修改Adobe Acrobat偏好设置,从根源避免弹窗
很多弹窗是可以通过Acrobat的内置设置关闭的,比如保存提示、OCR自动检测提示等,你可以在脚本开头先配置这些选项,从根源减少弹窗:
tell application "Adobe Acrobat Pro" -- 全局关闭警报弹窗 set display alerts to false -- 关闭保存时的确认提示 set save without prompt to true -- 如果涉及扫描件PDF,关闭自动OCR提示 tell preferences set auto OCR to false end tell end tell
这个方法更高效,推荐优先尝试,能大幅减少后续的弹窗处理逻辑。
方案3:添加错误捕获,处理弹窗引发的脚本中断
有时候弹窗会直接触发AppleScript的错误中断,你可以用try...on error块捕获错误,并针对性处理:
repeat with aFile in fileSet set currentFile to aFile as text set currentFileName to name of aFile set outFile to txtFolder & text 1 thru -5 of currentFileName & ".txt" try tell application "Adobe Acrobat Pro" open currentFile export active document to file outFile as text close active document saving no end tell on error errMsg number errNum -- -1708是常见的用户交互阻塞错误码,可根据实际情况调整 if errNum = -1708 then tell application "System Events" -- 直接点击当前弹窗的确认按钮 click button "确定" of window 1 of application process "Adobe Acrobat" end tell -- 重新尝试处理当前文件 tell application "Adobe Acrobat Pro" open currentFile export active document to file outFile as text close active document saving no end tell end if end try end repeat
关键注意事项
- 务必给脚本和Acrobat开启辅助功能权限:在系统偏好设置→安全性与隐私→隐私→辅助功能中,添加Script Editor和Adobe Acrobat程序,否则System Events无法控制弹窗。
- 弹窗的标题和按钮名称要和你实际遇到的一致(比如英文环境是"OK",中文是"确定"),需要对应修改代码里的文字。
内容的提问来源于stack exchange,提问作者Parzival
相关产品推荐
相关产品推荐

