Zoom in and Zoom out Page in selenium

Though such scenarios are not common in automation activities, you may encounter need to simulate browser zoom operation. These scenarios are common if you need to carry out accessibility testing.

In this tutorial, we have implemented Selenium zoom example with Java’s Action class.

Zoom In and Zoom Out operations are carried out by ‘CTRL +’ and ‘CTRL – ‘ key press respectively.

We will simulate these commands in Selenium WebDriver using Action class. Commands for those are Keys.chord(Keys.CONTROL, Keys.ADD) and Keys.chord(Keys.CONTROL, Keys.SUBTRACT). Similarly for zooming back in to the default level, Keys.chord(Keys.CONTROL, “0”) command is used.

To apply zoom on web page, we need to reference it with its HTML tag by using driver.findElement(By.tagName(“html”)) code. Now, let’s see the above commands in action with below code.

import org.openqa.selenium.By;
import org.openqa.selenium.Keys;
import org.openqa.selenium.Point;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;

public class ZoomInZoomOutExample {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		FirefoxDriver driver = new FirefoxDriver();
		driver.manage().window().maximize();
		driver.get("http://www.testingbar.com /");

		//To zoom In page 4 time using CTRL and + keys.
		for (int i = 0; i < 4; i++) {
			driver.findElement(By.tagName("html")).sendKeys(Keys.chord(Keys.CONTROL, Keys.ADD));
		}

		//To zoom out page 4 time using CTRL and - keys.
		for (int i = 0; i < 4; i++) {
			driver.findElement(By.tagName("html")).sendKeys(Keys.chord(Keys.CONTROL, Keys.SUBTRACT));
		}
		//To set browser to default zoom level 100%
		driver.findElement(By.tagName("html")).sendKeys(Keys.chord(Keys.CONTROL, "0"));

		driver.quit();
	}
}

Leave a Reply

Your email address will not be published. Required fields are marked *