Luís Soares
Luís Soares

Reputation: 6212

How to pass functions to Selenium's JavaScript executor?

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?

Upvotes: 0

Views: 144

Answers (1)

pguardiario
pguardiario

Reputation: 54992

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

Upvotes: 1

Related Questions