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:

Leave a Comment