How to inject javascript into page before page loads with selenium

Viewed 509

I'm trying to inject javascript into a page so that it runs before any other scripts are loaded/executed.

I have searched around and seen multiple suggestions saying that this is possible via the Devtool API and calling Page.addScriptToEvaluateOnNewDocument but I can't seem to get it to work.

This is what I have tried:

from selenium import webdriver

driver = webdriver.Chrome()
driver.get(url)
driver.execute_cdp_cmd('Page.addScriptToEvaluateOnNewDocument', {'source': 'alert("This is an alert.")'})

The code runs without any error, but no alert is shown in the browser. What am I missing?

1 Answers

you should add the code after creating the driver but before you get the web page

from selenium import webdriver

driver = webdriver.Chrome()
driver.execute_cdp_cmd('Page.addScriptToEvaluateOnNewDocument', {'source': 'alert("This is an alert.")'})
driver.get(url)
Related