-1

I'm trying to add some JS functions to a page but not sure how do it without assigning the function to the window object.

The following will work:

driver.execute_script("console.log('lalala');")
driver.execute_script("function momo(){console.log('lalala')};momo();")

But trying to do:

driver.execute_script("function momo(){console.log('lalala')};")
driver.execute_script("momo();")

will fail:

WebDriverException: Message: unknown error: momo is not defined

I know assigning the function to the window:

driver.execute_script("window.momo = function(){console.log('lalala')};")

will solve the issue, but maybe there is another way to do it?

Thanks.

Captain_Meow_Meow
  • 2,341
  • 5
  • 31
  • 44

3 Answers3

1

Maybe this answers the question:

driver.execute_script("window.momo = () => console.log('lalala');")

I'm just rewriting that in a more modern syntax.

pguardiario
  • 53,827
  • 19
  • 119
  • 159
  • this is the same function as in the question. but much more elegant... I still think there is no way to avoid using `window` in the script – Moshe Slavin Dec 06 '18 at 10:16
1

maybe you can create script element

driver.execute_script("""
(function(){
    s = document.createElement('script');
    s.textContent = 'function momo(){console.log("lalala")};';
    document.body.appendChild(s);
})();
""")
driver.execute_script("momo();")
ewwink
  • 18,382
  • 2
  • 44
  • 54
0

You are trying to introduce a new element to the window dom hence the error:

WebDriverException: Message: unknown error: momo is not defined

Your solution is probably the only one unless you try to manipulate an existing element!

In other words, you can add a JS function to any element that is already on the page.

This is the idea of the scope of the window dom.

You can understand more by reading this answer here.

Moshe Slavin
  • 5,127
  • 5
  • 23
  • 38