Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to handle popup window using selenium webdriver with Java

Tags:

selenium

popup

Please help, I'm new in Selenium. I try to automate eCommerce website and I have problem to handle popup window. Here is the scenario:

  1. Go to http://www.lampsplus.com
  2. Click on Sale link in the header section.
  3. Click on the 1st item/product displayed on the page. (This will show the product page).
  4. On the product page, click on the red Add To Cart button. (This will add a product to cart and display a popup).
  5. On the popup, click the dark-grey Continue Shopping button. (This will close the popup.)

I stuck on step 5 (Error message: Unable to locate element "Continue shopping button") Here is my code before step 5:

 WebDriver d1 = new FirefoxDriver();
d1.manage().window().maximize();
d1.get("http://www.lampsplus.com");
d1.findElement(By.name("hdr_sale")).click();
d1.findElement(By.xpath(".//*[@id='sortResultContainer60238']/a[2]/span")).click();
d1.findElement(By.id("pdAddToCart")).click(); //This is step 4
//Here is suppose to be some code which handles the popup - my problem
d1.findElement(By.id("aContinueShopping")).click();  //This is step 5

I'm aware about .getWindowHandle(); method. I tried several variations of it and none of them worked. Can anyone give me an idea how to handle it. Many thanks! I use Java.

Note: I don't work for LampsPlus and not try to promote their products, this website was chosen for training purposes only.

like image 446
Artem Avatar asked Mar 04 '26 11:03

Artem


1 Answers

The element aContinueShopping is contained within an iframe.

You'll have to switch to the iframe using:

WebElement frameID = d1.findElement(By.Css("#add-to-cart>iframe"));
d1.SwitchTo().Frame(frameID);
d1.findElement(By.id("aContinueShopping")).click();

There's no 'name' or 'id' on the iframe, so you'll have to use a WebElement or a numeric to find it.

Once you're done with that iframe, you'll switch back to 'top' by using:

d1.SwitchTo().DefaultContent();
like image 195
Richard Avatar answered Mar 06 '26 01:03

Richard