MLShivaPrasad MLShivaPrasad - 5 months ago 38
Java Question

Unable to execute Selenium WebDriver command on Javascript function enabled button

I am referring to http://www.w3schools.com/jsref/tryit.asp?filename=tryjsref_onclick_copy. On clicking the button, it is supposed to copy the value in field1 to field2. I tried to automate it with selenium webdriver.
I am using

WebDriver
commands as:

driver.get("http://www.w3schools.com/jsref/tryit.asp?filename=tryjsref_onclick_copy");
driver.findElement(By.xpath(".//button[@onclick='myFunction()']")).click();


But I got the error:

org.openqa.selenium.NoSuchElementException: Unable to locate element: {"method":"xpath","selector":".//button[@onclick='myFunction()']"}
Command duration or timeout: 20.11 seconds


After that I tried:

JavascriptExecutor jse = (JavascriptExecutor)driver;
jse.executeScript("document.getElementById(\"field2\").value = document.getElementById(\"field1\").value;");


This time I got the error:

org.openqa.selenium.WebDriverException: document.getElementById(...) is null

Answer

Your button is inside an iframe. You have to switch to the frame before find the element. See code below:

driver.get("http://www.w3schools.com/jsref/tryit.asp?filename=tryjsref_onclick_copy");  
driver.switchTo().frame(driver.findElement(By.id("iframeResult"))); 
driver.findElement(By.xpath(".//button[@onclick='myFunction()']")).click();
Comments