3

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 Answer 1

2

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) 
Sign up to request clarification or add additional context in comments.

2 Comments

This throws an error: ``` raise exception_class(message, screen, stacktrace, alert_text) selenium.common.exceptions.UnexpectedAlertPresentException: Alert Text: This is an alert. Message: unexpected alert open: {Alert text : This is an alert.} (Session info: chrome=92.0.4515.107) ```
works fine for me! try to accept alert in the code the error disapears

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.