如何遍历Chrome所有窗口并按配置文件名称激活指定窗口?
遍历并激活指定Chrome配置文件的窗口
macOS 下通过 zsh + AppleScript 实现
Chrome在macOS上的窗口标题会以配置文件名称作为前缀(比如工作 - Google Chrome),可以利用这一点筛选并激活目标窗口。
创建一个zsh脚本(比如activate-chrome-profile.zsh):
#!/usr/bin/env zsh # 指定要激活的配置文件名称 TARGET_PROFILE="工作" # 用AppleScript遍历Chrome窗口并激活匹配的窗口 osascript <<EOF tell application "Google Chrome" repeat with w in windows set windowTitle to title of w if windowTitle starts with "$TARGET_PROFILE - " then set index of w to 1 return end if end repeat end tell EOF
给脚本添加执行权限:
chmod +x activate-chrome-profile.zsh
运行脚本即可激活对应配置文件的Chrome窗口,若有多个匹配窗口,会激活第一个找到的。
Linux 下通过 zsh + wmctrl/xdotool 实现
Linux上同样可以通过窗口标题前缀匹配配置文件,结合wmctrl和xdotool工具实现:
- 先安装依赖工具:
# Debian/Ubuntu系 sudo apt install wmctrl xdotool # Fedora/RHEL系 sudo dnf install wmctrl xdotool
- 创建zsh脚本(比如
activate-chrome-profile.zsh):
#!/usr/bin/env zsh TARGET_PROFILE="工作" # 查找匹配配置文件的Chrome窗口ID WINDOW_ID=$(wmctrl -l | grep "$TARGET_PROFILE - Google Chrome" | awk '{print $1}') if [ -n "$WINDOW_ID" ]; then # 激活窗口 xdotool windowactivate $WINDOW_ID else echo "未找到对应配置文件的Chrome窗口" fi
添加执行权限后运行即可。
补充说明
- 如果你的Chrome窗口标题格式不同(比如配置文件名称在其他位置),可以调整脚本里的匹配规则。
- 若需要激活所有匹配的窗口,可修改脚本去掉
return(macOS)或者循环处理所有找到的窗口ID(Linux)。
内容的提问来源于stack exchange,提问作者wit4r7
相关产品推荐
相关产品推荐

