Reputation:
I am trying to generate or popup a java-script alert window with a string message from within the Selenium Java program while it is running. I read somewhere that we can execute javascript within Selenium as like..
You can directly execute javascript on a hidden element and set the attribute:
WebDriver driver;
JavascriptExecutor js = (JavascriptExecutor) driver;
js.executeScript("document.getElementById('auth_login_password').setAttribute('value', val );");
driver.ExecuteScript(string.Format("document.getElementById('cred-password-inputtext').value='{0}';",password));
How do I modify to write out a java-script alert? If it was feasible, I would like to use it as a debug tool too.
Upvotes: 0
Views: 9075
Reputation: 1868
For creating the javascript alert you can use this:
public void triggerAlert(String alertMessage){
JavascriptExecutor js = (JavascriptExecutor) driver;
js.executeScript("alert('"+alertMessage+"');");
}
But you should add the parameter to chromeOptions for not accepting the alert by default
ChromeOptions options = new ChromeOptions();
options.setUnhandledPromptBehaviour(UnexpectedAlertBehaviour.IGNORE);
Upvotes: 1
Reputation: 3384
Add following lines in your code where you want to receive an alert:
JavascriptExecutor js = (JavascriptExecutor) driver;
js.executeScript("alert('I am an alert box!')");
Upvotes: 1