Search code examples
javaseleniumselenium-webdriverautomated-testsawtrobot

Download a file in IE11 with Selenium and Robot class


I try to download a file in IE11 with Selenium WebDriver and Robot class, I am using IntelliJ and running test on a Selenium Grid with IE11.

I don't use element.click() function, because the controls stop there, hence I use sendKeys to focus on donwload button. Download popup appears, here comes Robot class. I try to press Alt+S to save file with help from Robot, but it doesn't press Alt+S on IE, it presses Alt+S on my IntelliJ instead !!!. Here is my code:

if (webBrowser.equalsIgnoreCase("ie")) {
   WebElement downloadReport = webDriver.findElement(By.id("clientReportDownload"));
   try {
        Robot robot = new Robot();
// sendKeys to focus on Download button and press Enter to download
        downloadReport.sendKeys("");
        downloadReport.sendKeys(Keys.ENTER);
        waitSeconds(2);
// wait for Download popup
        robot.setAutoDelay(250);
// simulate presse Alt + S to save file  -> It presses Alt+S on IntelliJ instead !!!
        robot.keyPress(KeyEvent.VK_ALT);
        robot.keyPress(KeyEvent.VK_S);
        robot.keyRelease(KeyEvent.VK_ALT);
        robot.keyRelease(KeyEvent.VK_S);
        waitSeconds(2);
        } catch (AWTException e) {
            e.printStackTrace();
        }
    }

Does anyone have a solution for this?


Solution

  • So, I realized that, after clicking on Download button, the focus on web browser gets lost somehow, so I need to set focus back on web browser before Robo commands start, with this for example:

    (JavascriptExecutor)webDriver.executeScript("window.focus();");
    

    then simulation of key press works!