0

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!

3
  • 4
    Have you ever initialized driver2 instance? Commented Sep 26, 2013 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". Commented Sep 26, 2013 at 22:38
  • I edited the original post. Unfortunately this thing doesn't help :( Commented Sep 27, 2013 at 11:27

2 Answers 2

2

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.

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

1 Comment

I edited the original post. Unfortunately this thing doesn't help :(
0

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!

Comments

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.