Why can't I do this

Why doesn't this:

Work the same as this:

Normally when you run the yellow box on say, for example, this page:

https://www.amazon.co.uk/MacFormat/dp/B008E88M64/

You get the result:

https://m.media-amazon.com/images/I/61oGrQzRl3L._SY679_.jpg

what_gives.kmmacros (8.4 KB)

The context:

I will be trying lots of different JS Paths, and they will all look end .src and save to a JS variable (like in the yellow box)

Hi, I suggest you check out this wiki page: action:Execute a JavaScript For Automation [Keyboard Maestro Wiki]

Bottom line, when passing information from Keyboard Maestro to the JXA script, you can't just embed variables like you'd do with some other actions. The same rule applies for shell scripts and AppleScripts.

Maybe some others with more JXA experience than me will correct me, but I think you could write the code to a file and then run the script file. But that would probably be more work than just following the instructions included in the wiki.

1 Like

You probably can do it. You're just not returning any value from it yet, and need to prefix your querySelector expression with return.

See, for example:

Extract text from a website - Questions & Suggestions - Keyboard Maestro Discourse

2 Likes

Tinker,

you have to use document.kmvar as documented in the link

actions:Execute a JavaScript in Browser [Keyboard Maestro Wiki]

image

myaction.kmactions (1.8 KB)

1 Like

document.kmvar is defined in the old syntax, but from the chevron at the left of @Tinker's JavaScript in Front Browser action's JS text field, we can see that this is KM 11.

By default Modern Syntax will be selected there.

In this case we don't need Keyboard Maestro variables at all, as it happens, but when we do need them, the modern syntax idiom is just a kmvar. prefix (to avoid the need for writing the users whole set of variables into the document object, where they would persist and be visible to other scripts)

All that is needed in this kind of case, with the default Modern Syntax setting of KM11, is an expression prefixed by return, like:

actions:Execute a JavaScript in Browser – Modern Syntax [Keyboard Maestro Wiki]

2 Likes

I'm on KM Version 10.2
The chevron just compresses the action in the UI

If you are still running Keyboard Maestro version 10 then the return can be omitted, but I think the problem may be with the evaluation of the .src property.

In your yellow example, .src is a property of a DOM object, and that whole expression is evaluated by JavaScript.

In your pink example, however, js_path is a Keyboard Maestro variable, and, like all KM variables, it's just a string.

Strings have no .src property.


If you want to get values from methods and properties of browser Document Object Model objects, you have to do that in JS, within an Execute JS action.