Can you pass KM variables into an "Execute Javascript in Chrome" action?

The red action fails (with variables) yet the green action works (without variables). Tried many permutations of this.

Also when I manually copy in the red action's value it works.

Doesn't work:

document.querySelector("#%js_list% > li:nth-child(%js_num%) > span > div > label > span").click()

Works:

document.querySelector("#list-travel_africa > li:nth-child(3) > span > div > label > span").click()

Does anyone have any experience using this action with variables rather than just raw text? Thanks.

The Wiki entry for Execute a JavaScript in Browser explains how to get variables in the JavaScript.

By the way, I found this by clicking the "gear" icon for the action, and selecting "Help". The only reason I mention this is that I had used KM for years before I even knew about this context-sensitive help, and I figure I can't be the only one. :smile:

1 Like

Thanks Dan. I had read that but didn't even realise it related to my issue (but can now see that it does!)

I'm not sure how to implement it syntactically in the KM action. I tried these 2 ways and both failed.

Failed:

document.querySelector("#document.kmvar.js_list > li:nth-child(document.kmvar.js_num) > span > div > label > span").click()

also failed:

var js_list = document.kmvar.js_list
var js_num = document.kmvar.js_num

document.querySelector("#js_list > li:nth-child(js_num) > span > div > label > span").click()

Screen Shot 2020-10-17 at 17.20.56

This syntax seems to work:

Screen Shot 2020-10-17 at 17.46.55

Can these 2 actions be collapsed into just 1 "Exec JS in Chrome" action?

(Alternatively writing my js variable to a .SCPT file and then executing from there also works.)

This works:

image

Use of the JavaScript eval() function is generally NOT recommended:

Recommendation
It is not recommended to use eval() because it is slow, not secure, and makes code unreadable and maintainable.

The reason that failed is that you did NOT concatenate the js_list variable correctly.
It should be:

document.querySelector("#" + js_list + " > li:nth-child(js_num) > span > div > label > span").click()

Try that and let us know if it now works for you.