2013-08-29 46 views
7

js.executeScript("return document.title") funziona correttamente come previsto ma non sono sicuro del motivo per cui il mio codice restituisce un errore puntatore nullo. cosa c'è di sbagliato qui?driver.executeScript() restituisce NullPointerException per un semplice javascript

String testJs= "function test() {arr = 111; return arr;}; test();"; 
    JavascriptExecutor js = (JavascriptExecutor) driver; 
    int a = (Integer) js.executeScript(testJS); 
+0

Cosa restituisce 'js.executeScript()'? Javadoc dice chiaramente 'Uno di Boolean, Long, String, List o WebElement. O null. –

+0

questo dove (ultima riga) il suo errore di annullamento del punto nullo – Sudhakar

risposta

11

Questo javascript

function test() {arr = 111; return arr;}; 
test(); 

chiama il metodo test(), ma non fa nulla con il risultato, vale a dire. non lo restituisce al chiamante.

Così

int a = (Integer) js.executeScript(testJS); 

torneranno null e cercare di essere dereferenziati che non riuscirà a causa dereferenziazione null getta NullPointerException.

Javadoc per JavascriptExecutor.html#executeScript(java.lang.String, java.lang.Object...)

Forse si desidera che il javascript

function test() {arr = 111; return arr;}; 
return test(); 

Questo funziona per me

System.setProperty("webdriver.chrome.driver", "C:\\Users\\me\\Downloads\\chromedriver.exe"); 
ChromeDriver driver = new ChromeDriver(); 
JavascriptExecutor executor = (JavascriptExecutor) driver; 
String js = "function test() {" + 
      "arr = 111; return arr;" + 
      "}; return test()"; 
Long a = (Long) executor.executeScript(js); 
System.out.println(a); 
+0

provato con il tuo suggerimento, continua a non funzionare – Sudhakar

+0

@Sudhakar Ha fallito con un 'ClassCastException'? Basta cambiare il tipo della tua variabile. Perché funziona per me. –

+0

Mi dispiace, ho sbagliato prima. Sì, il tuo suggerimento funziona perfettamente. Avevo trascurato la linea importante 'Uno di Boolean, Long, String, List o WebElement. Oppure null'. Grazie per il tuo tempo. Apprezzalo. – Sudhakar

0

Sì, la cosa fondamentale è non dimenticare inserire il ritorno, fe :

Long dateNow = (Long) jse.executeScript("return Date.now()"); 
Problemi correlati