0

Let's say I have a JS function like that:

function someFunction(callback) {
   callback()
}

and I want to call it from Selenium. for normal arguments (e.g. strings, arrays, integers, maps, HTML Elements) I can do:

driver.executeScript("someFunction(arguments[0])", "() => console.log('hi')")

and Selenium automatically converts/escapes the arguments. but if an argument is a function, then it's passed as a string. the call above becomes:

someFunction("() => console.log('hi')")

but it should have been:

someFunction(() => console.log('hi'))

is there a way to tell Selenium that the passed argument is a function?

2
  • 1
    you'd just pass the function and the call to the function as a string... it's a script so it's not interpreted yet, so you should be fine. I.e. you send "someFunction(() => console.log('hi')); " along with the function you are calling: "function someFunction(callback) { callback() }" ... as part of the same string... no need to pass as argument. Commented Nov 8, 2022 at 23:11
  • that makes sense for static strings. but if you want to make something generic, it's a bit more painful and you lose the benefits of Selenium arguments conversions (e.g. in maps and lists). look at the hack I had to do: github.com/lsoares/selenium-testing-library/blob/main/lib/src/… Commented Nov 9, 2022 at 10:47

1 Answer 1

1

with eval:

driver.executeScript("""
  var fn = eval(arguments[0])
  fn()
""", "() => console.log('hi')")

Note: I don't know how to escape quotes in java, this is python-style

Sign up to request clarification or add additional context in comments.

2 Comments

that's interesting but it is only for raw status cases. if you have a map of options and one option can be a function it's not so easy. this is a hack I had to do github.com/lsoares/selenium-testing-library/blob/main/lib/src/…
Not really, eval works for other types. eval("2") => number, eval("'2'") => string

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.