Before explaining Lightbox in theoretical way, I would like to show it to you in the below image first:
So lightbox is nothing but a script, which is used to overlay images, videos, web forms etc on the top of the pages, by dimming out the rest of the web page as shown in the above image.
Handling lightbox using Selenium WebDriver
Using Selenium WebDriver, handling lightbox is a very simple thing.
Unlike alerts, frames and windows, we dont have to switch to the lightbox for performing operations on it. The reason behind this is that the lightbox is part of the same web page.
Now, lets use Selenium to open the lightbox and perform operations on the lightbox like closing it using the 'x' button on the lightbox by following the below steps:
1. Open Firefox browser and browse http://omayo.blogspot.nl/p/lightbox.html as shown below:
2. Right click on the image and select 'Inspect in Firepath' option as shown below:
3. XPath for the image, will be generated by the Firepath as shown below:
4. Copy the above XPath generated by Firepath, and used it in Selenium code to click on the image as shown below:
Note: The reason behind clicking the above image is to open the lightbox. i.e. The image is programmed in such a way that, on clicking it, the lightbox opens.
5. Execute the above code and observe that the image will be clicked and the lightbox will be opened in the browser as shown below:
6. Now, lets perform the operations on the lightbox, by trying to click the 'x' button on the lightbox. First, we need to right click on the 'x' button and select 'Inspect in Firepath' option as shown below:
7. Observe that the XPath for the 'x' option on the lightbox will be generated by Firepath as shown below:
8. Copy the generated XPath and use it in Selenium code, for clicking the 'x' button on the lightbox as shown below:
9. Execute the above code and observe that the last statement in the code will perform operations on the lightbox by clicking 'x' option on it to close. Observe that the lightbox got closed as shown below:
Even though the lightbox looks like a pop-up / alert , we dont have to switch to it for performing operations on it using Selenium. Simply treat the lightbox as part of the page, locate elements as usual and perform operation on the elements without any need of switching to the lightbox.