我们正在使用jxbrowser版本6.21(在撰写本文时为最新)。
如果脚本陷入无限循环,则jxbrowser只会冻结并且保持无响应。我等了2分钟以上。
有什么办法可以顺利处理吗?
现代浏览器会检测到此情况,并向用户显示一个叠加层以停止脚本。
SSCCE:具有以下内容的html文件:
<html>
<body>
<script>
function badLoop() {
var nextTime = new Date().getTime();
while (true) {
var now = new Date().getTime();
if (now > nextTime) {
console.log('badLoop() running: ' + now);
nextTime = now + 500;
}
}
}
</script>
<input type="button" value="startLoop" onClick="badLoop()" />
</body>
</html>
测试可与其他浏览器一起运行:
jxbrowser可以吗?完全自动还是需要用户确认?
答案 0 :(得分:1)
以下是一个示例,该示例演示了如何在JxBrowser中拦截相应的onRenderUnresponsive
事件并检测到网页没有响应:
public class BrowserSample {
public static void main(String[] args) {
Browser browser = new Browser();
BrowserView view = new BrowserView(browser);
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
frame.add(view, BorderLayout.CENTER);
frame.setSize(700, 500);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
browser.addRenderListener(new RenderAdapter() {
@Override
public void onRenderUnresponsive(RenderEvent event) {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
JOptionPane.showMessageDialog(view, "The web page is unresponsive.");
}
});
}
});
browser.loadHTML("<html>\n"
+ " <body>\n"
+ " <script>\n"
+ " function badLoop() {\n"
+ " var nextTime = new Date().getTime();\n"
+ " while (true) {\n"
+ " var now = new Date().getTime();\n"
+ " if (now > nextTime) {\n"
+ " console.log('badLoop() running: ' + now);\n"
+ " nextTime = now + 500;\n"
+ " }\n"
+ " }\n"
+ " }\n"
+ " </script>\n"
+ " <input type=\"button\" value=\"startLoop\" onClick=\"badLoop()\" />\n"
+ " </body>\n"
+ "</html>");
}
}