Search code examples
javascriptpythonseleniumcode-injection

How to execute JavaScript from file


I am trying to launch a webpage in Firefox browser using python-Selenium web driver and to inject java script code on that loaded page.

from selenium import webdriver
from selenium.webdriver.common.keys import Keys
driver= webdriver.Firefox()
driver.get("https://www.python.org")

by the above code webpage is launched. Now my requirement is to add the js code to it.

driver.execute_script('''alert("java Script injected");''')

adding the above line to the code inject the single line js to webpage creating a dialog box showing "java Script injected".

What I actually want is to inject a Java Script code written in a file named jscode.js to the webpage launched using selenium web driver in python language.


Solution

  • If you want to execute JavaScript from file, try below code:

    from selenium import webdriver
    from selenium.webdriver.common.keys import Keys
    driver= webdriver.Firefox()
    driver.get("https://www.python.org")
    
    with open('/path/to/jscode.js') as f:
        java_script = f.read()
    
    driver.execute_script(java_script)