Shuo
Shuo

Reputation: 8937

Run javascript file with selenium chrome driver

Followed the start guide, I can run a javascript snippet by using driver.execute(). How can I run external javascript files, which load some external modules itself.

Possible ways I can come up with:

  1. Concatenate all required files into a single large file and then load it into a string and run it with driver.execute(). Possibly with help of a minifier.

  2. Execute a small snippet to load all required js files.

  3. Maybe modify the html before browser render it?

Any suggestions?

Upvotes: 1

Views: 7863

Answers (1)

alecxe
alecxe

Reputation: 473873

You can actually load scripts dynamically via execute_script(). Here is an example use case where jquery library is dynamically loaded to support HTML5 drag&drop simulation:

The key functionality is the javascript code that is executed via execute_async_script() (taken from here) that adds a script element to head via document.createElement() on the fly.

The first link has a working example in Python, the second one has it in Java.

Upvotes: 1

Related Questions