Selenium WebDriver zoom in/out page content
Asked Answered
R

16

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.

Reitareiter answered 22/2, 2013 at 12:54 Comment(1)
Just out of curiosity: what are you testing here? A Javascript app that intercepts these controls?Stonecutter
P
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.

Padnag answered 22/2, 2013 at 13:25 Comment(8)
I get an error for your C# solution that SendKeys has no method with IElement and three strings.Ancohuma
@Sunnyday Yeah, this answer is 6 years old, perhaps things have changed. Try going for the <body> element instead? I honestly do not know whether this approach will work anymore. It worked back then.Embarkation
thanks for reply. This should be in driver options, but I could not find it.Fumigate
I still do not understand why zoom level will affect how webdriver find elements.Fumigate
@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.Embarkation
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();Prioress
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???Neille
Yes, at this time this solution (tried Java against Chrome) no longer works. :(Olives
I
13

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);
Idolla answered 15/4, 2017 at 0:49 Comment(3)
This worked for me with Selenium v3.3.1 and ChromeDriverMisgovern
modifying document.body.style.zoom messes up the page layout of complex pages; it's not a general solutionOptimism
unfortunately the robot.keyPress doesn't seem to work on a dedicated Windows Jenkins slave; using Chrome & chromedriver 119.0.6045.*Ci
C
10

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);
Cyanohydrin answered 4/7, 2022 at 4:0 Comment(3)
This should be the correct answer since it addresses the reset of pages and doesn't fail in remote environments like the robot.sendKeys solutionsCi
The second argument is not available on Google source page or the peter.sh website (peter.sh website is officially given as a reference in Google chromedriver website)Easterling
JavascriptExecutor js = (JavascriptExecutor) driver; js.executeScript("document.body.style.zoom='25%'"); As you told javascript executor only work for the current page, if we need to update to all other pages we have to update all these places with the above scriptUnderfur
P
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.

Pullman answered 17/7, 2015 at 18:57 Comment(8)
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).Lyell
According to this this makes it zoom in CSS, not Chrome itself. I tried it in Firefox, and didn't workDasilva
Looking a way to zoom out Firefox window using Python. Any help please?Lenitalenitive
Have you the approach used in this question? Selenium's action chains worked for me in Firefox, but not in Chrome. I tested this about a year ago, so it might have changed.Pullman
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?Baggott
Hi @Baggott did you solve your issue? am facing the sameAdrenal
@Baggott and Prabhu maybe you could open a new question? I think the approach depends if you're using Firefox (geckodriver) or chromedriver.Pullman
modifying document.body.style.zoom messes up the page layout of complex pagesOptimism
R
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));
Robinrobina answered 5/9, 2013 at 11:29 Comment(3)
What's the library to be imported for this ? I don't see any helpful suggestions in eclipse.Hottentot
I've imported org.openqa.selenium.By; and org.openqa.selenium.WebElement; but I need the appropriate library for "Keys"Hottentot
from selenium.webdriver.common.keys import KeysDisembowel
W
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.

Wixted answered 25/11, 2016 at 9:45 Comment(1)
Thank you for your help, but I want to do it for all browsers, is there any way to do itCompensate
G
2

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%';");
Gramarye answered 21/3, 2017 at 9:17 Comment(1)
modifying document.body.style.zoom messes up the page layout of complex pages; it's not a general solutionOptimism
S
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);
Sextan answered 10/5, 2022 at 12:34 Comment(0)
K
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%';");
Kept answered 15/7, 2016 at 2:43 Comment(0)
T
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)`
Topsail answered 2/6, 2017 at 7:46 Comment(0)
F
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%'");
Finecut answered 8/2, 2018 at 10:33 Comment(1)
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"Hottentot
A
1

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

Adiaphorism answered 8/8, 2023 at 0:24 Comment(1)
To set default zoom level, you have to set partition.default_zoom_level.x. To those wondering how the value is calculated, it is base-1.2 logarithm of the zoom level. In the answer that would be log(0.8) / log(1.2) = −1,2239Semantic
H
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();
        }
Henton answered 18/2, 2016 at 11:49 Comment(1)
I know right. But guess what. I figured it out. .SendKeys(Keys.Control + Keys.Subtract).Perform();Carolyn
C
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.

Cheeky answered 12/4, 2017 at 4:47 Comment(0)
O
0

11-17-2017 Update

var html = page.FindElement(By.XPath("/html"));
html.SendKeys(Keys.Control + "0" + Keys.Control);
Ousley answered 17/11, 2017 at 15:43 Comment(0)
F
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%"');
Funiculus answered 22/3, 2021 at 23:14 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.