Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

Spent 1 day on finding the solution to the following problem:

Can't execute even simple js code using selenium WD. It always returns NullPointerException. Already read tonns of answers but still can't find the reason. The code below is the code after 1 day investigation (I just have tried everything):

WebDriver driver2;
JavascriptExecutor js = (JavascriptExecutor)driver2;
driver.get(baseUrl+ "/");
js.executeScript("return showAlert()");

Here is the original code that is not working as well:

    public class DPT_class {
      private WebDriver driver;

      @Before
      driver = new FirefoxDriver();
      JavascriptExecutor js = (JavascriptExecutor) driver;

      @Test
      //some testing code here
      driver.get(baseUrl+ "/");
      js.executeScript("return showAlert()");
}

the same thing for any other js code such as alert(document.title) with and without return and quotes. *baseUrl is predefined of course.

Thanks!

share|improve this question
4  
Have you ever initialized driver2 instance? –  Smit Sep 26 '13 at 22:22
    
Agree with @Smit on this one: the example code given does not assign a value to driver2, in which case js will not have a value either. Your compiler should be complaining that you are using a value which isn't "definitely assigned". –  rutter Sep 26 '13 at 22:38
    
I edited the original post. Unfortunately this thing doesn't help :( –  dred17 Sep 27 '13 at 11:27

2 Answers 2

up vote 2 down vote accepted

As @Smit says, and per your NullPointerException

You've never actually initialized your WebDriver object, and you're attemting to cast a null object, to JavaScriptExecutor.

Depending on what sort of browser you want to use, you are able to do..

WebDriver driver = new ChromeDriver();
WebDriver driver = new FirefoxDriver(); // etc...

Also, why are you attempting to use 2 driver objects? You should only have 1. Keep your object named driver.

share|improve this answer
    
I edited the original post. Unfortunately this thing doesn't help :( –  dred17 Sep 27 '13 at 9:12

Have changed

private WebDriver driver;
      driver = new FirefoxDriver();
      JavascriptExecutor js = (JavascriptExecutor) driver;

to

WebDriver driver = new FirefoxDriver();
  JavascriptExecutor js = (JavascriptExecutor) driver;

Have no idea why but it works now! Thanks a lot!

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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