线程“AWT-EventQueue-0"中的异常尝试执行 Javascript 时出现 java.lang.NullPointerException [英] Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException when trying to execute Javascript

查看:71
本文介绍了线程“AWT-EventQueue-0"中的异常尝试执行 Javascript 时出现 java.lang.NullPointerException的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在通过我的 Java 应用程序加载的 DOM html 页面上执行名为returnAllLinkTexts()"的 Javascript 函数.下面的代码由一个 Swing 按钮执行.

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

偶尔我会收到以下异常.Java 应用程序不会终止或崩溃.

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)

我已经尝试了以下方法来继续重​​试大约 20 次,但它甚至没有达到这一点.异常立即在@ 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++;
}

更新:

这是Javascript函数returnAllLinkTexts();

This is the Javascript function returnAllLinkTexts();

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

$('a', document).each(function() {
    mydata.push($(this).text()); 
});

return mydata;
}

推荐答案

我唯一能想到的为什么 returnAllLinkTexts 会中断(因此你得到 null)是在 jQuery 加载之前调用它.

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

如果可能,请尝试在页面加载完成后调用 browser.executeJavascript 否则按照其他人已经建议的那样检查 null,并且您可以继续尝试调用它(例如使用计时器),直到它不为 null.

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.

由于您已经将返回值用作字符串,因此您可以返回字符串开头,例如:

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.

这篇关于线程“AWT-EventQueue-0"中的异常尝试执行 Javascript 时出现 java.lang.NullPointerException的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆