无需辅助功能权限获取前端应用并打乱窗口索引的方法
无需辅助功能权限打乱应用窗口顺序的AppleScript方案
核心逻辑
直接与目标应用的AppleScript接口通信,完全避开System Events——只有系统级控制工具才需要辅助功能权限,而调用应用自身的自动化接口属于应用内操作,无需额外授权(只要该应用支持AppleScript自动化,大部分原生应用和主流第三方应用都支持)。
实现前提
你需要提前知晓目标应用的名称(比如Finder、Safari),如果必须处理任意前端应用,那绕不开辅助功能权限(因为获取当前前端应用属于系统级信息,必须依赖System Events或同类工具)。
通用代码示例(以Finder为例)
tell application "Finder" set windowList to windows if length of windowList < 2 then return -- 窗口数不足2时无需打乱 -- 获取当前窗口索引并打乱 set originalIndices to indices of windowList set shuffledIndices to shuffleList(originalIndices) -- 重新设置窗口层级 repeat with i from 1 to length of windowList set index of item i of windowList to item i of shuffledIndices end repeat end tell -- 辅助函数:随机打乱列表 on shuffleList(theList) set listLength to length of theList repeat with i from listLength down to 2 set j to random number from 1 to i set temp to item j of theList set item j of theList to item i of theList set item i of theList to temp end repeat return theList end shuffleList
适配其他应用的注意事项
- 大部分应用的窗口集合都是
windows,索引index属性可写(index=1代表最前端窗口) - 若部分应用不支持修改
index,可以尝试通过activate或set visible to true配合循环移动窗口的方式间接打乱顺序 - 不确定应用是否支持AppleScript时,可在Script Editor中通过
文件 > 打开字典选择目标应用查看其自动化接口文档
内容的提问来源于stack exchange,提问作者user3310334
相关产品推荐
相关产品推荐

