1

So I have to upload a document, and the popup for file explorer loads and my code can find the document I need, but how do I then switch back to my original browser? Here is the code:

        driver.SwitchTo().ActiveElement().SendKeys("C:\\Users\\Saurav\\Downloads\\GGPrezi.pptx");

It is able to select the document but now I need to get back to the original browser, how do I do that?

  • 1
    Are you sure that your code can find the document? Because from what I know selenium webdriver cannot interact with OS pop-ups. – ilm Feb 17 '16 at 9:03
1

Selenium cannot handle any OS based dialogues like file browser. So if the upload element is visible on the page, then instead of using switchTo() function you should directly use sendKeys() function to upload a document as shown below:

driver.findElement(By.id("uploadElement")).sendKeys("C:\\Users\\Saurav\\Downloads\\GGPrezi.pptx");

So the control will always be on the original browser.

For more information just go through following link: Upload a file in Selenium Webdriver using sendKeys

If you want to learn to switch between multiple windows using selenium, then below mentioned link might help: https://stackoverflow.com/questions/34741257/how-to-change-between-pages-with-selenium

Hope this helps :)

0

I think you need to use driver.switch_to.default_content(). I am not sure but the Java version of webdriver should be

 driver.switchTo().defaultContent();
0

@Saurav -

  1. When you are able to select your document perfectly, anyways control/focus will be automatically shifted to your main browser window. Isn't it really?

  2. Still if you wanted to handle from code, I will suggest to go through How to handle browser pop-up. Core concept will remain same.

  3. If you want to use sendKeys() to upload a file using selenium web driver, make sure that the input element is visible on the page. Once the element is visible, you should simply use below mentioned code:

driver.findElement(By.id("myUploadElement")).sendKeys("absolute path of the file");

You should not click on the browse button as it will open windows dialogue box and selenium web driver won't work.

myUploadElement is the id of that element and in sendKeys() you have to specify the absolute path of the content you want to upload (Image,video etc). Selenium will do the rest for you.

If sendkeys() wont work at all, then you can also use SikuliX to handle uploading files.

SikuliX can be used as it automates everything that you see on the screen. It uses image recognition to identify and control GUI components.

Give a try, Hope it helps !

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.