Search Titles of Safari or Chrome Tabs in Multiple Windows and Bring Match to Front

Not sure of your exact use case, but I've sketched something here (just for Chrome) which:

  • seems to find and activate the first tab which includes a given string.
  • was tested this evening with Chrome 86.0.4240.183

Activate a Chrome tab containing a given string.kmmacros (22.0 KB)

JS Source
(() => {
    'use strict';

    // Activate first Chrome tab with a title
    // which includes the given string.

    // Rob Trew @2020

    // main :: IO ()
    const main = () => {
        const
            s = toLower(
                Application(
                    'Keyboard Maestro Engine'
                ).getvariable('tabString')
            ),
            ws = Application('Google Chrome').windows;
        return either(
            // Explanatory message,
            x => x
        )(
            // or title and url of activated tab.
            x => x
        )(
            bindLR(
                0 < ws.length ? (
                    Right(ws.at(0))
                ) : Left('No windows open in Chrome')
            )(frontWindow => {
                const
                    tabIndex = frontWindow.tabs()
                    .findIndex(
                        x => toLower(x.title()).includes(s)
                    );
                return bindLR(
                    -1 !== tabIndex ? (
                        Right(tabIndex)
                    ) : Left('No match found in tabs.')
                )(index => {
                    const tab = (
                        frontWindow.activeTabIndex = (1 + index),
                        frontWindow.activeTab()
                    );
                    return Right(
                        `[${tab.title()}](${tab.url()})`
                    )
                });
            })
        );
    };

    // --------------------- GENERIC ---------------------

    // Left :: a -> Either a b
    const Left = x => ({
        type: 'Either',
        Left: x
    });


    // Right :: b -> Either a b
    const Right = x => ({
        type: 'Either',
        Right: x
    });


    // bindLR (>>=) :: Either a -> 
    // (a -> Either b) -> Either b
    const bindLR = m =>
        mf => undefined !== m.Left ? (
            m
        ) : mf(m.Right);


    // either :: (a -> c) -> (b -> c) -> Either a b -> c
    const either = fl =>
        // Application of the function fl to the
        // contents of any Left value in e, or
        // the application of fr to its Right value.
        fr => e => 'Either' === e.type ? (
            undefined !== e.Left ? (
                fl(e.Left)
            ) : fr(e.Right)
        ) : undefined;


    // toLower :: String -> String
    const toLower = s =>
        // Lower-case version of string.
        s.toLocaleLowerCase();

    // MAIN ---
    return main();
})();
1 Like