How to Open First Link in Chrome Search

I want to make a macro that opens the first link in a Google Chrome search. I know no JavaScript and made my code after a few google searches. When I run this in the console of my browser (after inspecting), it works as expected, although this is surely not the best or cleanest way to do this. I tried attaching it to run in Chrome through Keyboard Maestro and it does nothing. I tried looking at the Keyboard Maestro wiki for some help and wasn't able to find anything very helpful. Is there a good way to make this work?

var urls = document.getElementsByTagName('a');
for (url in urls) {
    try {
        // This is just a very wide-reacher filter for some of the searches
        if (urls[url].href.indexOf("google") === -1 ) {
            if (!urls[url].href) {
                // Checks if the URL contains anything to not open an invalid link
                continue;
            }
            window.open(urls[url].href);
            break;
        }
    } catch (TypeError) {
        // Nothing
    }
}
1 Like

You can't do this from an external context.

You need to return the URL to your macro and then use an Open a URL action to open it in Google Chrome.

Thank you! That worked!

var urls = document.getElementsByTagName('a');
for (url in urls) {
    try {
        // This is just a very wide-reacher filter for some of the searches
        if (urls[url].href.indexOf("google") === -1 ) {
            if (!urls[url].href) {
                // Checks if the URL contains anything to not open an invalid link
                continue;
            }
            var final = urls[url].href;
            break;
        }
    } catch (TypeError) {
        // Nothing
    }
}
final
1 Like