hammerspoon

How to find specific chrome tab across all spaces using hammerspoon


I want to use hammerspoon to find one specific chrome tab across al chrome windows across all spaces. The only way I was able to achieve this was using osascript, which I don't like much because it means to use a big multi-line string inside Lua. I will prefer to use native hammerspoon methods with Lua.

Just in case, here is my version using osascript that works perfectly:

local function osa()
    local tabName = "whatsapp"
    local script = [[
  tell application "Google Chrome" to activate
  tell application "Google Chrome"
    set found to false
    repeat with theWindow in windows
      repeat with theTab in (tabs of theWindow)
        if the title of theTab contains "%s" then
          set found to true
          set index of theWindow to 1
          return id of theTab
        end if
      end repeat
    end repeat
    return found
  end tell
]]

    local success, windowID, errors = hs.osascript.applescript(string.format(script, tabName))

    print(success, windowID, type(windowID), hs.inspect(errors))
    if success == false then
        hs.alert.show("Tab with name '" .. tabName .. "' not found.")
    else
        hs.alert.show("Tab '" .. tabName .. "' found and brought to front.")
    end
end

Solution

  • This is the final solution that I'm using. I took it from here and modified it to be more general. It works for any chromium browser, so I generalised it so you can use it with chrome, or brave or whatever you want. Here is the module:

    return function(browserName)
        local function open()
            hs.application.launchOrFocus(browserName)
        end
        local function jump(url)
            local script = ([[(function() {
          var browser = Application('%s');
          browser.activate();
    
          for (win of browser.windows()) {
            var tabIndex =
              win.tabs().findIndex(tab => tab.url().match(/%s/));
    
            if (tabIndex != -1) {
              win.activeTabIndex = (tabIndex + 1);
              win.index = 1;
            }
          }
        })();
      ]]):format(browserName, url)
       hs.osascript.javascript(script)
        end
        return { open = open, jump = jump }
    end
    
    

    And this is an example usage

    Chrome = require("browser")("Google Chrome")
    Chrome.jump("localhost:3000")