Home > Net >  Execute js function (which is defined in a execute_script()) in another execute_script()
Execute js function (which is defined in a execute_script()) in another execute_script()

Time:08-12

Consider:

driver.execute_script("function main(){console.log('this is main');}")
driver.execute_script(f"return main()")

The second execute_script() will cause selenium.common.exceptions.JavascriptException: Message: javascript error: main is not defined How can I fix this without merging the two execute_script()?


Clarification
I want to "save" the js function so that in the future I can call the function with execute_script(), without redefining it. For example:

driver.execute_script(open("js_functions.js").read())
# Do sth
driver.execute_script(f"return funcA()")
# Do sth
driver.execute_script(f"return funcB()")
# Do sth
driver.execute_script(f"return funcA()")

Currently, I have to do like this

# Do sth
js_funcs = open("js_functions.js").read()   "\n"
driver.execute_script(js_funcs   "return funcA()")
# Do sth
driver.execute_script(js_funcs   "return funcB()")
# Do sth
driver.execute_script(js_funcs   "return funcA()")

CodePudding user response:

Change this:

driver.execute_script("function main(){console.log('this is main');}")

To this:

driver.execute_script("window.main = () => console.log('this is main')")

Explanation: the function was in another function's scope.

  • Related