0

am using javascriptexecutor with Selenium (IEdriver used on Edge (IE compatibility)). There is a input with w BROWSE button that brings up a Windows file search. (See picture). Selenium can't handle Windows file browser.

The HTML looks like this

<span class="options">
    <input id="importSource" title="Source" size="50" type="file" 
     name="importSource" requiredfield="1">
</span>

Doing a sendKeys(file) to the element will bring up the file browser. I wanted to use JavascriptExecutor, so I did

[![enter image description here][1]][1]WebElement ele = driver.findElement(By.xpath("//input[@id='importSource']"));
JavascriptExecutor jse = (JavascriptExecutor) driver;
String script = "arguments[0].setAttribute('value', '" + fileName + "');";
jse.executeScript(script, ele);

fileName is the name of a file. But when I look at the box it is empty and when I inspect ele.getAttribute("value") it is blank.

If I manually click browse and select a file and do an inspect ele.getAttribute("value") it shows the filename. So setting it should work but doesn't.

is there some reason the Javascript is not working? The value of ele is not null as I can get the attribute. (In the picture I removed any company-specific confidential info, but it is just text).

1 Answer 1

1

As far as I know, this is by design. You cannot set file input via JavaScript as this is a security violation. Therefore you cannot achieve this requirement by executing scripts on the page.

But sendKeys work. Because this method bypasses security restrictions, it is an operating system-level event and is not browser-specific. If it is just a simple text input element, this requirement can be easily achieved through javascript. But input element of file type will call the file system.

Just refer to this similar case and relevant doc:

how does selenium webdriver upload files to the browser?

https://aosabook.org/en/v1/selenium.html

Sign up to request clarification or add additional context in comments.

4 Comments

Yes but when I do sendKeys() it opens a Windows file selection box, which selenium can't handle. It probably shouldn't but it does. I tried appending a Keys.ENTER to the file name but it treats it as part of the filename. That is, if I use sendKeys() on a name of a non-existent file I get an error that the file does not exist. If I use an existing filename then I do not get the error but the filechooser opens and is blank.
Yes, if the file does not exist, it will throw an exception. You can try-catch it and prompt the user.
you can't prompt the user in automation
You can execute script alert, something like this:` String script = "alert('file not exist..')"; jse.executeScript(script); `

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.