30

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.

Ripon Al Wasim
  • 36,924
  • 42
  • 155
  • 176
user2099471
  • 303
  • 1
  • 3
  • 5

17 Answers17

30

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.

Benjamin Loison
  • 3,782
  • 4
  • 16
  • 33
Petr Janeček
  • 37,768
  • 12
  • 121
  • 145
  • I get an error for your C# solution that SendKeys has no method with IElement and three strings. – Azimuth Sep 05 '16 at 08:47
  • @Sunnyday Yeah, this answer is 6 years old, perhaps things have changed. Try going for the `` element instead? I honestly do not know whether this approach will work anymore. It worked back then. – Petr Janeček Jun 22 '19 at 23:40
  • thanks for reply. This should be in driver options, but I could not find it. – eastwater Jun 23 '19 at 15:52
  • I still do not understand why zoom level will affect how webdriver find elements. – eastwater Jun 23 '19 at 15:54
  • @Sunnyday At least back in 2013, this was because zooming was browser-specific, without any public API that would control it. On top of that, IE in general had no nice API at all, so everything was based on JS actions. And when JS tells you an element is at location XY, but the actual location is different due to a zoom being applied, that's when you're in trouble. I do not know whether Selenium 3 or 4 solves this, though. Nor whether modern browsers report zoomed element locations correctly. – Petr Janeček Jun 23 '19 at 20:31
  • BTW, in C# it would actually be: IWebElement html = driver.FindElement(By.TagName("html")); new Actions(driver) .SendKeys(html, Keys.Control + "0" + Keys.Null) .Perform(); – William Jul 16 '19 at 03:09
  • i tried that C# code, but i am getting no such element exception with the html tag, is it supposed to locate the element 'html' with the wrong zoom??? – anandhu Aug 24 '20 at 11:01
12

Here are two ways the zoom level can be altered with Java (one is for Chrome and the other is for Firefox):


Chrome

When using v̲e̲r̲s̲i̲o̲n̲ ̲3̲.̲3̲.̲1 of the Selenium Java Client Driver and C̲h̲r̲o̲m̲e̲D̲r̲i̲v̲e̲r̲ ̲2̲.̲2̲8, the following works (where the number in single quotes represents the zoom level to use; 1 = 100%, 1.5 = 150%, etc.):

JavascriptExecutor executor = (JavascriptExecutor)driver;
executor.executeScript("document.body.style.zoom = '1.5'");

Firefox

The zoom level can be modified with the following:

  1. The aforementioned Java Client Driver
  2. G̲e̲c̲k̲o̲D̲r̲i̲v̲e̲r̲ ̲v̲0̲.̲1̲5̲.̲0
  3. These classes:
    java.awt.Robot
    java.awt.event.KeyEvent

First of all, instantiate the Robot class:

Robot robot = new Robot();

This code causes the zoom level to decrease:

robot.keyPress(KeyEvent.VK_CONTROL);
robot.keyPress(KeyEvent.VK_MINUS);
robot.keyRelease(KeyEvent.VK_CONTROL);
robot.keyRelease(KeyEvent.VK_MINUS);

This code causes the zoom level to increase:

robot.keyPress(KeyEvent.VK_CONTROL);
robot.keyPress(KeyEvent.VK_EQUALS);
robot.keyRelease(KeyEvent.VK_CONTROL);
robot.keyRelease(KeyEvent.VK_EQUALS);
Benjamin Loison
  • 3,782
  • 4
  • 16
  • 33
User253489
  • 169
  • 1
  • 4
9

Python approach working for me, except you have to specify the zoom level:

driver.execute_script("document.body.style.zoom='zoom %'")

Have 'zoom%' = whatever zoom level you want. (e.g. '67%'). This works for Chromedriver, which doesn't seem to accept the send_keys commands.

Benjamin Loison
  • 3,782
  • 4
  • 16
  • 33
Ben
  • 2,308
  • 2
  • 18
  • 25
  • 1
    Looks like this javascript snippet also works for Safari, and I assume PhantomJS and any Webkit based browser. It doesn't appear to work on Firefox (tested on v47). – David Aug 20 '16 at 00:46
  • 2
    According to [this](https://stackoverflow.com/questions/31986557/zoom-in-and-out-chrome-browser-using-selenium-with-python) _this makes it zoom in CSS, not Chrome itself._ I tried it in Firefox, and didn't work – Rodrigo Laguna Jun 01 '17 at 19:21
  • 2
    Looking a way to zoom out Firefox window using Python. Any help please? – user2436428 Nov 21 '17 at 07:28
  • Have you the approach used in [this question](https://stackoverflow.com/questions/28111539/can-we-zoom-the-browser-window-in-python-selenium-webdriver)? Selenium's [action chains](http://selenium-python.readthedocs.io/api.html#module-selenium.webdriver.common.action_chains) worked for me in Firefox, but not in Chrome. I tested this about a year ago, so it might have changed. – Ben Nov 21 '17 at 14:49
  • Hi @Ben, Sorry for replying to a very old message. I tried using the javascript method to zoom out but after the zoom out the elements are not interactable. I am not able to click on the elements. I tried delay after the javascript step and before running any other action. Is there anything I am missing? – Vin Apr 23 '20 at 22:22
  • Hi @Vin did you solve your issue? am facing the same – Prabhu Jul 17 '20 at 15:25
  • @Vin and Prabhu maybe you could open a new question? I think the approach depends if you're using Firefox (geckodriver) or chromedriver. – Ben Jul 18 '20 at 16:06
  • 2
    modifying `document.body.style.zoom` messes up the page layout of complex pages – movAX13h Feb 03 '22 at 10:42
4

Zoom in | Zoom out Feature on Windows

Zoom in

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

Zoom out

html.sendKeys(Keys.chord(Keys.CONTROL, Keys.SUBTRACT));

Zoom in | Zoom out Feature on MAC

Zoom in

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

Zoom out

html.sendKeys(Keys.chord(Keys.COMMAND, Keys.SUBTRACT));
Benjamin Loison
  • 3,782
  • 4
  • 16
  • 33
Prashanth Sams
  • 19,677
  • 20
  • 102
  • 125
3

Changing the zoom level through javascript execution is OK but it only apply to the first page displayed. The succeeding pages will return to 100% zoom level. The best solution I found so far is to set the Chrome Options' device scale factor.

ChromeOptions options = new ChromeOptions();
options.addArguments("force-device-scale-factor=0.75");
options.addArguments("high-dpi-support=0.75");
WebDriver driver = new ChromeDriver(options);
Benjamin Loison
  • 3,782
  • 4
  • 16
  • 33
elfwine
  • 41
  • 3
2

The most robust approach

Before you start with Internet Explorer and Selenium Webdriver Consider these two important rules.

  1. The zoom level :Should be set to default (100%) and
  2. The security zone settings : Should be same for all. The security settings should be set according to your organisation permissions.

How to set this?

Simply go to Internet explorer, do both the stuffs manually. Thats it. No secret.

Do it through your code.

Method 1:

//Move the following line into code format
DesiredCapabilities capabilities = DesiredCapabilities.internetExplorer();

capabilities.setCapability(InternetExplorerDriver.IGNORE_ZOOM_SETTING, true);

System.setProperty("webdriver.ie.driver","D:\\IEDriverServer_Win32_2.33.0\\IEDriverServer.exe");

WebDriver driver= new InternetExplorerDriver(capabilities);

driver.get(baseURl);

//Identify your elements and go ahead testing...

This will definetly not show any error and browser will open and also will navigate to the URL.

BUT This will not identify any element and hence you can not proceed.

Why? Because we have simly suppressed the error and asked IE to open and get that URL. However Selenium will identify elements only if the browser zoom is 100% ie. default. So the final code would be

Method 2 The robust and full proof way:

DesiredCapabilities capabilities = DesiredCapabilities.internetExplorer();

capabilities.setCapability(InternetExplorerDriver.IGNORE_ZOOM_SETTING, true);

System.setProperty("webdriver.ie.driver","D:\\IEDriverServer_Win32_2.33.0\\IEDriverServer.exe");

WebDriver driver= new InternetExplorerDriver(capabilities);

driver.get(baseURl);

driver.findElement(By.tagName("html")).sendKeys(Keys.chord(Keys.CONTROL,"0"));
//This is to set the zoom to default value
//Identify your elements and go ahead testing...

Hope this helps. Do let me know if further information is required.

Benjamin Loison
  • 3,782
  • 4
  • 16
  • 33
NiNa
  • 111
  • 1
  • 4
2

Below snippet will set the browser zoom to 80%

String zoomJS;
JavascriptExecutor js = (JavascriptExecutor) driver;
zoomJS = "document.body.style.zoom='0.8'";  
js.executeScript(zoomJS);
Benjamin Loison
  • 3,782
  • 4
  • 16
  • 33
1

I know this is late, but in case if you don't want to use action class (or getting any errors, as I did) you can use pure JavaScript to do so.

Here is the code

((IJavaScriptExecutor) Browser.Driver).ExecuteScript("document.body.style.zoom = '70%';");
Benjamin Loison
  • 3,782
  • 4
  • 16
  • 33
Right QA
  • 11
  • 2
1

For Zoom In to 30%(or any other value you wish but in my case 30%) use

JavascriptExecutor jse = (JavascriptExecutor)driver;
jse.executeScript("document.body.style.zoom = '30%';");
Benjamin Loison
  • 3,782
  • 4
  • 16
  • 33
  • 1
    modifying `document.body.style.zoom` messes up the page layout of complex pages; it's not a general solution – movAX13h Feb 03 '22 at 10:43
1

I am using Python 3.5.; I got the same problem as you. I thought you must use Chrome as browser.

I used PhantomJs to finally solve this problem:

from selenium.webdriver.common.keys import Keys
from selenium import webdriver
browser = webdriver.PhantomJS()
browser.get('http://www.*.com')
print(browser.title)
c=browser.find_element_by_tag_name("body")
c.send_keys(Keys.LEFT_CONTROL+Keys.Add)`
Benjamin Loison
  • 3,782
  • 4
  • 16
  • 33
thonner
  • 11
  • 1
1

you may use "Keys.chord" method for Zoom out and Zoom in

Zoom OUT

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

when you are done with your work and want to reset browser back to 100% then use below code If you want to click on any element, so before click event you may reset you browser window to 100 % after you may click on it.

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

You may user Java script code as well for Zoom OUT

JavascriptExecutor executor = (JavascriptExecutor)driver;
executor.executeScript("document.body.style.zoom = '110%'");
Benjamin Loison
  • 3,782
  • 4
  • 16
  • 33
Ankit jain
  • 4,198
  • 4
  • 19
  • 24
  • What's the library to be imported for this ? I don't see any helpful suggestions in eclipse. I've imported org.openqa.selenium.By; and org.openqa.selenium.WebElement; but I need the appropriate library for "Keys" – murphy1310 May 30 '18 at 15:01
0

Seems that approach proposed for C# doesn't work anymore.

Approach for C# that works for me in WebDriver version 2.5 is:

        public void ZoomIn()
        {
             new Actions(Driver)
                .SendKeys(Keys.Control).SendKeys(Keys.Add)
                .Perform();
        }

        public void ZoomOut()
        {
            new Actions(Driver)
               .SendKeys(Keys.Control).SendKeys(Keys.Subtract)
               .Perform();
        }
Benjamin Loison
  • 3,782
  • 4
  • 16
  • 33
Denis Koreyba
  • 3,144
  • 1
  • 31
  • 49
0

Using Robot class worked for me:

for(int i=0; i<3; i++){
    Robot robot = new Robot();
    robot.keyPress(KeyEvent.VK_CONTROL);
    robot.keyPress(KeyEvent.VK_MINUS);
    robot.keyRelease(KeyEvent.VK_CONTROL);
    robot.keyRelease(KeyEvent.VK_MINUS);
}

this will zoom out 3 times.

Benjamin Loison
  • 3,782
  • 4
  • 16
  • 33
0

11-17-2017 Update

var html = page.FindElement(By.XPath("/html"));
html.SendKeys(Keys.Control + "0" + Keys.Control);
Benjamin Loison
  • 3,782
  • 4
  • 16
  • 33
roncansan
  • 2,310
  • 6
  • 27
  • 34
0

You can use Selenium's driver to execute a script that will zoom in or out for you.

Firefox

await driver.executeScript('document.body.style.MozTransform = "scale(3)"');
await driver.executeScript(
  'document.body.style.MozTransformOrigin = "top"'
);

This will result in zooming in by 300% and will scroll to top.

Chrome

await driver.executeScript('document.body.style.zoom = "300%"');
Benjamin Loison
  • 3,782
  • 4
  • 16
  • 33
Hatem
  • 285
  • 1
  • 8
0

You can set the zoom level for Chrome from ChromeOptions with this:

options.setUserPreferences({
    // Set zoom level to 80%
    "partition": {
        "per_host_zoom_levels": {
            "x": {
                "localhost": {
                    "last_modified": "13335927042283476",
                    "zoom_level": -1.2239010857415447
                }
            }
        }
    }
})

Here's a relevant reference which led me to the solution: Selenium WebDriver — Start Chrome with DevTools open to Console panel

sarimarton
  • 151
  • 1
  • 7
0

After all comments above, I noticed that the suggestion below was not mentioned yet. It resolved the issue I had in my project.

Java

driver.manage().window().fullscreen();
Furkan
  • 505
  • 4
  • 12