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

Question:

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()")
Asked By: vcth4nhh

||

Answers:

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.

Answered By: pguardiario
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.