Generating Alert In Selenium Webdriver using JavascriptExecutor

If you need to generate alert during your software test case execution then you can use java script Executor in selenium webdriver software testing tool. Java Script Executor is very helpful interface of selenium webdriver because using it we can execute any java script. I think manual alert generation in webdriver test is required only in rare case but main purpose of this post is to explore Java Script Executor. You can view more examples of JavascriptExecutor on THIS LINK.

If you remember, we can generate alert in selenium IDE software testing tool too using "runScript" command. THIS POST will describe you how to generate alert in selenium IDE software testing tool using "runScript" command with example.

Now let me describe you how to generate alert in selenium webdriver software automation if required during test case execution of your software web application.

Copy bellow given @Test method part of generate alert using javascript example and replace it with the @Test method part of example given on THIS PAGE(Note : @Test method is marked with pink color in that linked page).

Example 3 : JavascriptExecutor to generate alert in selenium webdriver
@Test
 public void test () throws InterruptedException 
 {  
  //Generating Alert Using Javascript Executor
  JavascriptExecutor javascript = (JavascriptExecutor) driver;
  javascript.executeScript("alert('Test Case Execution Is started Now..');");
  Thread.sleep(2000);
  driver.switchTo().alert().accept();
 }

In above example, Java Script Executor will simply execute the javascript and generate alert. You can your own alert text in it. Try it in your own software application test if required.

5 comments:

  1. On typing " javascript.executeScript("alert('Test Case Execution Is started Now..');");" i get the following error notification,
    "The method executeScript(String) is undefined for the type javasxcriptexecutor

    ReplyDelete
  2. This comment has been removed by the author.

    ReplyDelete
  3. var username="abc"
    .execute(function(result,username){
    alert(username)
    })

    am getting the result as undefined

    ReplyDelete
  4. var username="abc"
    .execute(function(result,username){
    alert(username)
    })

    am getting result as undefined

    ReplyDelete
  5. Worked perfectly fine.. JavasrciptExecutorObject.executeScript("alert('Thanks a lot for this tutorial');");

    ReplyDelete