What does execute_script() in Selenium does What does execute_script() in Selenium does selenium selenium

What does execute_script() in Selenium does


execute_script method allows to execute JavaScript passed as string argument

Note that you can pass data from Python code into JavaScript code using arguments, e.g.

hello = "Hello"friends = " friends"browser.execute_script('alert(arguments[0], arguments[1]);', (hello,  friends))

enter image description here


execute_script()

execute_script() synchronously executes JavaScript in the current window/frame.

execute_script(script, *args)where:    script: The JavaScript to execute    *args: Any applicable arguments for your JavaScript.    

This method is defined as:

   def execute_script(self, script, *args):       """       Synchronously Executes JavaScript in the current window/frame.       :Args:        - script: The JavaScript to execute.        - \\*args: Any applicable arguments for your JavaScript.       :Usage:           ::               driver.execute_script('return document.title;')       """       if isinstance(script, ScriptKey):           try:               script = self.pinned_scripts[script.id]           except KeyError:               raise JavascriptException("Pinned script could not be found")       converted_args = list(args)       command = None       if self.w3c:           command = Command.W3C_EXECUTE_SCRIPT       else:           command = Command.EXECUTE_SCRIPT       return self.execute(command, {           'script': script,           'args': converted_args})['value']

Examples

A couple of examples:

  • To open a new blank tab:

    driver.execute_script("window.open('','_blank');")
  • To open a new tab with an url:

    driver.execute_script("window.open('https://www.google.com');")
  • To retrieve the page title:

    driver.execute_script('return document.title;')
  • To scroll inti view an element:

    driver.execute_script("arguments[0].scrollIntoView(true);",element)

References

You can find a couple of relevant detailed discussions in: