Can I Pass JavaScript Code in a Parameter?

More specifically, can I pass a JS Path, i.e., a document.queryselector(...), as a parameter and have a couple of subroutine actions, which run JavaScript text, test whether the element that the path denotes exists, and if so, click() it?

So far I haven't got it to work. If I hard-code a literal document.queryselector(...) in the text script in the action it works.

The test herewith, although not a subroutine, illustrates what doesn't work. Note that the second action returns the string, document.querySelector(..., not the result of executing the query. This is understandable. But I wonder if there's a way to do this.

Test.kmmacros (2.4 KB)

My experience with JavaScript is short and shallow. After posting the above question, it occurred to me that JS might have an eval() function. Indeed, it does. I'll experiment with that after a night's sleep.

Not quite sure that I've followed, but one way or another defining a function should help.

JavaScript functions are objects with a .toString() method, so you can always obtain their source code as a JS string.

As a fractionally less deprecated alternative to eval you can use something like.

const fn = new Function( someFunctionCodeString )

const result = fn()

Function - JavaScript | MDN


I read about Function and eval(); the latter seems simpler and in my case there are no security nor performance concerns -- I'm running this code only within KM on my local Mac, not on a server. So I used eval(document.kmvar.Local_jsPath).click(); and it works!