简体   繁体   中英

How to generate a javascript alert with a small string message using Selenium Java WebDriver

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.

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);

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!')");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM