Cannot run Javascript with Webdriver due to "unresolved type" error

6.7k Views Asked by At

Hi there I am unable to run JavaScript using Web driver due to an Unresolved compilation problem, can anyone point out where I am going wrong so I can run a real simple line of JavaScript when running a selenium web driver script?

package Check;

import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;

public class java {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        FirefoxDriver driver = new FirefoxDriver();
        driver.get("https://www.google.co.uk/search?q=dreams");
        WebDriver driver2 = new AnyDriverYouWant();
        JavascriptExecutor js;
        if (driver instanceof JavascriptExecutor) {
            js = (JavascriptExecutor)driver;
        }
        js.executeScript("function showAlert() { alert('success'); }; showAlert()");
        driver.quit();
    }
}

Error details:

Exception in thread "main" java.lang.Error: Unresolved compilation problem: 
AnyDriverYouWant cannot be resolved to a type

at Check.java.main(java.java:13)
4

There are 4 best solutions below

0
On

I needed to force the page to wait and to instantiate the variable unconditionally, here is the revised code that works:

package Check;

import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.firefox.FirefoxDriver;

public class jave {

    public static void main(String[] args) throws InterruptedException {
        // TODO Auto-generated method stub
        FirefoxDriver driver = new FirefoxDriver();
        driver.get("https://www.google.co.uk/search?q=dreams");
        //WebDriver driver2 = new AnyDriverYouWant();
        JavascriptExecutor js = (JavascriptExecutor)driver;
        js.executeScript("function showAlert() { alert('success'); }; showAlert()");
        Thread.sleep(5000);
        driver.quit();
    }

}
1
On

It looks like you are trying to instantiate a class that does not exist, which is:

  WebDriver driver2 = new AnyDriverYouWant();

remove this line (it does not look like its needed) and it should work.

0
On

I downloaded the latest chrome driver from here and the latest selenium jar file (2.44) and using this code and I could make the element be clickable:

// Find an element and define it
WebElement elementToClick = D9.findElement(By.xpath("xpathcode"));

// Scroll the browser to the element's Y position
((JavascriptExecutor) D9).executeScript("window.scrollTo(0,"+elementToClick.getLocation().y+")");

// Click the element
elementToClick.click();
0
On

I faced this exact issue today. It was solved by explicitly writing the import statement for the javascriptExecutor class