Google Chrome – How to Bring an Existing GMail Tab to the Front

Full disclosure: I'm certain I "borrowed" this code from someone here, but I can't remember who. I am dirt.

This is a subroutine I use for that and more. You can pass it a regular expression (or just a substring) of the tab title you want to focus on.

var kme = Application("Keyboard Maestro Engine")
kme.includeStandardAdditions = true
var app = Application("Google Chrome")
app.includeStandardAdditions = true


function run(argv) {

// Get KM local/instance var
var theRegExp = kme.getvariable("RegExp");

	let theTabExp = new RegExp(theRegExp)
	let found = 0
	for (let winIdx = 0; winIdx < app.windows().length; winIdx++) {
		if (found) break
		for (let tabIdx = 0; tabIdx < app.windows()[winIdx].tabs().length; tabIdx++) {
			if (app.windows()[winIdx].tabs()[tabIdx].title().match(theTabExp)) {
    				app.activate()
    				app.windows[winIdx].visible = true
    				app.windows[winIdx].activeTabIndex = tabIdx + 1 // Focus on tab
    				app.windows[winIdx].index = 1 // Focus on this specific Chrome window
			found = 1
			break
			}
		}
	}
}