Nacho Escursell
Nacho Escursell

Reputation: 161

Selenium Remote WebDriver get canvas content using Chrome in headless mode

I'm trying to get Whatsapp QR with Selenium WebDriver on remote machine.

I using latest version on docker package

selenium/standalone-chrome:latest

The point is, if I try the following code without headless on, works smooth.

Maybe my configuration isnt correct.

Any ideas?

    ChromeOptions dCap = new ChromeOptions();
    dCap.setHeadless(true);
    dCap.setCapability("platform", "LINUX");
    dCap.setCapability("version", "latest");
    dCap.addArguments("disable-infobars");
    dCap.addArguments("--start-maximized");
    dCap.addArguments("--disable-extensions");
    dCap.addArguments("--disable-gpu");
    dCap.addArguments("--window-size=1920x1080");
    dCap.addArguments("--enable-javascript");        

    String driverPath = System.getProperty("user.dir") + "/exe/chromedriver";
    System.setProperty("webdriver.chrome.driver", driverPath);

    URL rutaProxy = new URL("http://localhost:4444/wd/hub");
    WebDriver driver = new RemoteWebDriver(rutaProxy, dCap);        
    driver.get("https://web.whatsapp.com/");

    WebDriverWait espera = new WebDriverWait(driver, 20);
    espera.until(ExpectedConditions.presenceOfElementLocated(By.cssSelector(".landing-main canvas")));
    WebElement canvas = driver.findElement(By.cssSelector(".landing-main canvas"));

    JavascriptExecutor js = (JavascriptExecutor)driver;
    String imagenBase64 = (String) js.executeScript("return arguments[0].toDataURL('image/png').substring(21);", canvas);

    //TEST
    byte[] imageByte = Base64.getDecoder().decode(imagenBase64.substring(1));
    ByteArrayInputStream bis = new ByteArrayInputStream(imageByte);
    BufferedImage image = ImageIO.read(bis);
    bis.close();

    File outputfile = new File("image.png");
    ImageIO.write(image, "png", outputfile);
    
    driver.close();

Upvotes: 1

Views: 649

Answers (1)

warlock
warlock

Reputation: 31

I've been in this situation, add more time delay between a action and a window popup, because the refresh of some DOM elements takes time. Enabling headless requires more latency than not enabling it.

Upvotes: 1

Related Questions