开发者

Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException when trying to execute Javascript

开发者 https://www.devze.com 2023-02-05 05:12 出处:网络
I am trying to execute Javascript function called \"returnAllLinkTexts()\" on the DOM html page loaded via my Java application. Below line is executed by a Swing Buton.

I am trying to execute Javascript function called "returnAllLinkTexts()" on the DOM html page loaded via my Java application. Below line is executed by a Swing Buton.

myscript = browser.executeJavascript("returnAllLinkTexts()").toString(); //Line 407

Once in a while I get the following exception. The Java application does not terminate or crash.

Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException com.demo.Main$BigButtonListener.actionPerformed(Main.java:407)

I have tried the following to keep retrying about 20 times but it doesn't even reach this point. Exception is raised immediately @ 407.

int st = 0;
while (myscript == null){
 myscript = browser.executeJavascript("gogo()").toString();                              if (myscript != null) break;
 if (shit == 20) break;
 sht++;
}

UPDATE:

This is the Javascript function returnAllLinkTexts();

function returnAllLinkTexts(){  
var mydata = new Array();

$('a', document).each(function() {
    myd开发者_如何学运维ata.push($(this).text()); 
});

return mydata;
}


The only thing I can think of why returnAllLinkTexts is breaking (thus you get null) is when it's called before jQuery was loaded.

If possible, try calling browser.executeJavascript after the page finished loading otherwise check for null as others already suggested and you can keep trying to invoke it (using timer for example) until it's not null.

Edit: since you're already using the return value as string, you can return string to begin with, for example:

return mydata.join(",");

Will return the links text separated with comma.


You're calling toString() on a potentially null object.

-> Firstly, I would surround with a try-catch block

But the question is why is the return value a possible-null? Check your return value in the function..

Nur


Don't unconditionally call toString() on a return value which may be null. Always check first for null!

0

精彩评论

暂无评论...
验证码 换一张
取 消