Execute Javascript: Variable not being parsed

Spent hours trying to figure out workarounds for this and I just can't find any. I would like to create a subroutine that calls this JS with a dynamic variable that's defined inside Keyboard Maestro.

document.getElementById('%Mum_URL%').click();

Don't know why but the variable isn't reaching Chrome.

When I put that string inside an Alert right next to the Execute JavaScript, it works perfectly. Mum_URL as a variable is being defined and being parsed fine.

Chrome's JS console is giving me errors like this:

VM22:5 Uncaught TypeError: Cannot read properties of null (reading 'click') at <anonymous>:5:37 at <anonymous>:6:4

When I click on that it shows the unparsed string:

(function () { var kmvar = { "Mum_URL" : "keepfit_setup", } document.getElementById('%Mum_URL%').click(); })()

I've tried all sorts of alternative syntax like ('" + %Mum_URL% + "') etc

Anyone able to help me out here? It's odd that it parses fine in the alert, but not in the JS console.

thx so much

The KM action "Execute JavaScript in Browser" does not allow you to use variables. Which totally sucks. But it's not an insurmountable problem.

The simplest solution is to build the JS in a variable, then save the variable to a temporary file, and have the "Execute JavaScript" using the file instead of a variable.

For example:

image

There are other more complicated solutions, including routines that create the Action dynamically, but I recommend starting with this method first.

2 Likes

holy moly. Wish I'd posted this days ago
Clunky as hell but it did the trick!!
Thanks so much Dan :pray:

Text tokens (that percentage syntax) are not processed in Execute [Code] actions, but in Keyboard Maestro 11+ you should be able to select the KM variable names that you want to read (but not write, from JS) in the drop-down menu behind the tiny chevron to the left of the code text field:

and then use the kmvar. prefix, as in kmvar.Mum_URL etc:

KM Variable values in 'Execute JavaScript in Browser' code.kmmacros (2.7 KB)


See the section on using KM variables in:
actions:Execute a JavaScript in Browser [Keyboard Maestro Wiki]

4 Likes

Tokens are not processed in any script text (JavaScript, Shell Script, AppleScript, etc) since expanding tokens in a script could cause all sorts of mayhem.

Variables can be passed to the Execute a JavaScript in Front Browser action by selecting the desired variables in the popup menu to the left of the script, and accessing them as kmvar.variable_name, etc kmvar.Mum_URL.

3 Likes

Something I didn't know. Thanks!

1 Like

And of course the variable could contain JSON, which allows you to pass more information.

1 Like