How to reference KM Variables in Text Scripts?

I am trying to execute a javascript in browser to get a link.

Here's it normally without variables. This javascript just gets the 10th page of a google search query if you're on page 1.

Here's it with me trying to implement variables. The Page number being the variable I'm trying to change. I just don't know how to syntax what I put as +pagenumber+.

Sidenote: Goal is here to get last page of google results for search queries 10 pages or under. I'm sure there's a better way to do this but this was my shoddy solution I'm trying to put together.

Try using this for your JavaScript and then you shouldn't need the loop:

Array.from(document.querySelectorAll('table#nav a.fl')).slice(-1)[0].href

This just grabs all the links out of the nav table at the end of the search results and converts them to an array, then takes the last one from the array and returns its href attribute.

As long as the last link isn't the current page, it should work no matter how many pages are in the results. I tested it with 2 pages and with 10 pages.


Awesome, thanks so much.

Could you help me with how do adapt this to a different web service? Not super experienced with javascript and not sure what would go in place of a.fl

HTML for one result is this

<button aria-label="Navigate to page 6" data-page-number="6" type="button" data-ember-action="" data-ember-action-332="332" data-is-animating-click="true">

This one doesn't have the href attribute so goal would be to either click the button or getting the page number value would be fine too since I could just adjust the it in the url

edit: code for clicking the button would be

document.querySelector('[aria-label="Navigate to page 6"]').click();



Answering your original question, if you look in the Execute a JavaScript in Browser action documentation (which you can get to by selecting Help from the gear menu in the action), the Using Keyboard Maestro Variables section covers how to access Keyboard Maestro variables from within such a JavaScript.