0

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
Danielo515
  • 5,996
  • 4
  • 32
  • 66

2 Answers2

1

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")
Danielo515
  • 5,996
  • 4
  • 32
  • 66
0

note: this answer is not the right answer to child tabs it only search through child windows

you can use hs.window.allWindows() (https://www.hammerspoon.org/docs/hs.window.html#allWindows ) to get the list of all windows and then filter by application

or you use the hs.window.filter ( https://www.hammerspoon.org/docs/hs.window.filter.html ) and create a filter with the Chrome app name or with the Chrome bundle identifier

muescha
  • 1,544
  • 2
  • 12
  • 22