如何用Hammerspoon在所有空间的Chrome窗口中查找指定标签页
用Hammerspoon原生Lua实现Chrome标签页全局查找
可以通过结合Hammerspoon的hs.application、hs.window模块与轻量的AppleScript片段实现,将核心逻辑用Lua处理,避免冗长的多行嵌入脚本:
local function findChromeTab(tabName) local chrome = hs.application.get("Google Chrome") if not chrome then hs.alert.show("Chrome is not running.") return false end -- 遍历所有Chrome窗口(覆盖所有空间) for _, win in ipairs(chrome:allWindows()) do -- 获取当前窗口的所有标签标题与ID local success, tabs = hs.osascript.applescript(string.format([[ tell application "Google Chrome" get {title, id} of tabs of window %d end tell ]], win:id())) if success then -- 在Lua中检查标签标题 for i, tabTitle in ipairs(tabs[1]) do -- 不区分大小写匹配,可改为`tabTitle == tabName`实现精确匹配 if string.find(string.lower(tabTitle), string.lower(tabName)) then -- 激活窗口并切换到目标标签 win:becomeMain() hs.osascript.applescript(string.format([[ tell application "Google Chrome" set active tab index of window %d to %d end tell ]], win:id(), i)) hs.alert.show(string.format("Tab '%s' found and brought to front.", tabName)) return true end end end end hs.alert.show(string.format("Tab with name '%s' not found.", tabName)) return false end -- 调用示例:查找标题包含"whatsapp"的标签 findChromeTab("whatsapp")
代码说明
chrome:allWindows():获取Chrome的所有窗口,包含当前空间以外的窗口,实现全局查找- 拆分AppleScript片段:仅用短小的脚本获取单个窗口的标签信息,避免大段嵌入代码
- Lua逻辑处理:用
string.find完成标签标题的匹配,示例为不区分大小写,可按需调整匹配规则 - 激活与切换:找到目标标签后,先激活对应窗口,再切换到目标标签,功能与原AppleScript一致
内容的提问来源于stack exchange,提问作者Danielo515
相关产品推荐
相关产品推荐

