how to zoom out the page with Chrome webdriver

12,126

The easiest way is to execute javascript:

JavascriptExecutor js = (JavascriptExecutor) driver;
js.executeScript("document.body.style.zoom='90%'");

or whatever zoom you need. PS I'm pretty bad in Java, so I'm sorry, if syntax is not quite correct

Share:
12,126
Gangadhar
Author by

Gangadhar

Updated on June 12, 2022

Comments

  • Gangadhar
    Gangadhar almost 2 years

    I have tried to zoom out the page with following code

    driver.findElement(By.tagName("html")).sendKeys(Keys.chord(Keys.CONTROL, Keys.SUBTRACT));
    

    This is working fine with Firefox webdriver. But It's not working with Chrome. It throws the following Exception

    org.openqa.selenium.WebDriverException: unknown error: cannot focus element
      (Session info: chrome=28.0.1500.71)
      (Driver info: chromedriver=2.3,platform=Linux 3.5.0-30-generic x86) (WARNING: The server did not provide any stacktrace information)
    Command duration or timeout: 53 milliseconds
    Build info: version: '2.37.0', revision: 'a7c61cb', time: '2013-10-18 17:15:02'
    System info: host: 'vtiger-desktop', ip: '127.0.1.1', os.name: 'Linux', os.arch: 'i386', os.version: '3.5.0-30-generic', java.version: '1.7.0_12-ea'
    Session ID: 918da5187e72caa1e68c49614c187dee
    Driver info: org.openqa.selenium.chrome.ChromeDriver
    Capabilities [{platform=LINUX, acceptSslCerts=true, javascriptEnabled=true, browserName=chrome, chrome={chromedriverVersion=2.3}, rotatable=false, locationContextEnabled=true, version=28.0.1500.71, cssSelectorsEnabled=true, databaseEnabled=true, handlesAlerts=true, browserConnectionEnabled=false, webStorageEnabled=true, nativeEvents=true, applicationCacheEnabled=false, takesScreenshot=true}]
        at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
        at sun.reflect.NativeConstructorAccessorImpl.newInstance(Unknown Source)
        at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(Unknown Source)
        at java.lang.reflect.Constructor.newInstance(Unknown Source)
        at org.openqa.selenium.remote.ErrorHandler.createThrowable(ErrorHandler.java:193)
        at org.openqa.selenium.remote.ErrorHandler.throwIfResponseFailed(ErrorHandler.java:145)
        at org.openqa.selenium.remote.RemoteWebDriver.execute(RemoteWebDriver.java:554)
        at org.openqa.selenium.remote.RemoteWebElement.execute(RemoteWebElement.java:268)
        at org.openqa.selenium.remote.RemoteWebElement.sendKeys(RemoteWebElement.java:89)
    
  • movAX13h
    movAX13h about 2 years
    modifying document.body.style.zoom messes up the layout of complex pages; it's not a general solution