Selenium WebDriver zoom in/out page content

user2099471 picture user2099471 · Feb 22, 2013 · Viewed 89.2k times · Source

How to change page zoom level in Selenium WebDriver? I tried:

driver.Keyboard().pressKey(Keys.Control);
driver.Keyboard().pressKey(Keys.Add);

But it doesn't work.

Answer

Petr Janeček picture Petr Janeček · Feb 22, 2013

Beware that Selenium assumes the zoom level is at 100%! For example, IE will refuse to start (throws an Exception) when the zoom level is different, because the element locating depends on this and if you changed the zoom level, it would click on wrong elements, at wrong places.


Java

You can use the Keys.chord() method:

WebElement html = driver.findElement(By.tagName("html"));
html.sendKeys(Keys.chord(Keys.CONTROL, Keys.ADD));

Use cautiously and when you're done, reset the zoom back to 100%:

html.sendKeys(Keys.chord(Keys.CONTROL, "0"));

C#

(since I realized C# bindings don't have the Keys.chord() method)

Or, you can use the Advanced User Interactions API like this (again, Java code, but it should work the same in C#):

WebElement html = driver.findElement(By.tagName("html"));

new Actions(driver)
    .sendKeys(html, Keys.CONTROL, Keys.ADD, Keys.NULL)
    .perform();

Again, don't forget to reset the zoom afterwards:

new Actions(driver)
    .sendKeys(html, Keys.CONTROL, "0", Keys.NULL)
    .perform();

Note that the naïve approach

html.sendKeys(Keys.CONTROL, Keys.ADD);

doesn't work, because the Ctrl key is released in this sendKeys() method. The WebElement's sendKeys() is different from the one in Actions. Because of this, the Keys.NULL used in my solution is required.