Selenium: How to Inject/execute a Javascript in to a Page before loading/executing any other scripts of the page?

Selenium has now supported Chrome Devtools Protocol (CDP) API, so , it is really easy to execute a script on every page load. Here is an example code for that:

driver.execute_cdp_cmd('Page.addScriptToEvaluateOnNewDocument', {'source': 'alert("Hooray! I did it!")'})

And it will execute that script for EVERY page load. More information about this can be found at:

  • Selenium documentation: https://www.selenium.dev/documentation/en/support_packages/chrome_devtools/
  • Chrome Devtools Protocol documentation: https://chromedevtools.github.io/devtools-protocol/tot/Page/#method-addScriptToEvaluateOnNewDocument

Leave a Comment