You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

AppleScript实现Finder窗口Bounds保存与恢复问题求助

解决Finder窗口位置保存与恢复的问题

一、修复GetFW脚本的报错问题

你遇到的Can’t get item 3 of every window错误,是因为错误地用索引访问窗口属性。正确的做法是直接获取每个Finder窗口的目标路径(替代名称,满足你的最终需求)和bounds属性。

以下是修正后的GetFW.applescript,会将窗口数据保存为JSON格式(方便后续解析):

set savePath to (path to desktop folder as text) & "FWData.json"
set fwData to {}

tell application "Finder"
    repeat with win in every window
        -- 获取窗口的目标文件夹路径
        set targetPath to POSIX path of (target of win as alias)
        -- 获取窗口的bounds数组
        set winBounds to bounds of win
        -- 将数据存入列表
        set end of fwData to {path:targetPath, bounds:winBounds}
    end repeat
end tell

-- 将列表转为JSON字符串(依赖系统自带的Python3)
set jsonString to do shell script "python3 -c 'import json, sys; print(json.dumps(" & fwData & "))'"
-- 写入文件
set fileRef to open for access file savePath with write permission
write jsonString to fileRef
close access fileRef

二、实现基于路径前缀匹配的窗口位置恢复

针对你的需求(进入子/父文件夹时仍能恢复位置),我们可以用路径前缀匹配:只要当前窗口的路径是保存路径的子路径,就使用对应的bounds。

以下是RestoreFW.applescript:

set savePath to (path to desktop folder as text) & "FWData.json"
-- 读取保存的JSON数据
set fileRef to open for access file savePath
set jsonString to read fileRef
close access fileRef

-- 解析JSON为AppleScript可处理的列表
set fwData to run script "return " & do shell script "python3 -c 'import json, sys; print(json.loads(sys.argv[1]))' " & quoted form of jsonString

tell application "Finder"
    repeat with currentWin in every window
        set currentPath to POSIX path of (target of currentWin as alias)
        set matchedBounds to missing value
        
        -- 遍历保存的数据,寻找前缀匹配的路径
        repeat with entry in fwData
            set savedPath to path of entry
            -- 检查当前路径是否以保存的路径为前缀
            if currentPath starts with savedPath then
                set matchedBounds to bounds of entry
                exit repeat
            end if
        end repeat
        
        -- 如果找到匹配项,恢复窗口位置
        if matchedBounds is not missing value then
            set bounds of currentWin to matchedBounds
        end if
    end repeat
end tell

三、关键细节说明

  • 用路径替代窗口名称:窗口名称可能重复(比如多个名为“Downloads”的文件夹),而路径是唯一标识,且支持前缀匹配,完美适配子文件夹场景。
  • JSON格式存储:相比纯文本,JSON结构化数据更容易解析,避免了手动处理字符串格式的麻烦。
  • 前缀匹配逻辑:通过starts with判断当前路径是否包含保存的路径作为前缀,这样进入子文件夹时,依然能匹配到父文件夹的窗口位置配置。

内容的提问来源于stack exchange,提问作者Max Well

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.19 14:57:20