我在我的应用程序中使用SWT浏览器。我需要在浏览器中的HTML页面上运行脚本。但是在完全加载页面之前运行脚本。那么如何让应用程序等到浏览器完成加载。我尝试过这样的事情。
completed = true;
browser.addProgressListener(new ProgressListener() {
@Override
public void completed(ProgressEvent event) {
completed = true; //say this is a global variable
}
@Override
public void changed(ProgressEvent event) {
completed = false;
System.out.println("Page changing");
}
});
//some other method
void m1()
{
browser.setText("blah blah blah");
while (completed == false)
{}
// EXECUTE THE SCRIPT NOW
}
但这不起作用!
这与Java SWT browser: Waiting till dynamic page is fully loaded类似,但没有解决方案。
答案 0 :(得分:1)
您可以定义BrowserFunction
并从JavaScript代码中调用它:
public static void main(String[] args)
{
Display display = new Display();
Shell shell = new Shell(display);
shell.setLayout(new FillLayout());
Browser browser = new Browser(shell, SWT.NONE);
new CustomFunction(browser, "theJavaFunction");
browser.setText("<style>#map { width: 100%; height: 300px; }</style><script src='http://maps.google.com/maps/api/js?sensor=false'></script><div id='map'></div><script>var map;function initialize() { var mapOptions = { zoom: 8, center: new google.maps.LatLng(-34.397, 150.644) }; map = new google.maps.Map(document.getElementById('map'), mapOptions);} google.maps.event.addDomListener(window, 'load', initialize);window.onload = function () { theJavaFunction(); };</script>");
shell.pack();
shell.setSize(600, 400);
shell.open();
while (!shell.isDisposed())
{
if (!display.readAndDispatch())
display.sleep();
}
display.dispose();
}
private static class CustomFunction extends BrowserFunction
{
CustomFunction(Browser browser, String name)
{
super(browser, name);
}
@Override
public Object function(Object[] arguments)
{
System.out.println("theJavaFunction() called from javascript");
return null;
}
}
答案 1 :(得分:1)
Baz给出了正确答案的方向。我会尝试将你的答案放在你的背景中:
private boolean loading; // Instance variable
createBrowserControl() { // Browser widget definition method
Browser b = ...; // Create the browser widget
browser.addProgressListener(new ProgressListener() {
@Override
public void completed(ProgressEvent event) {
loading = false;
}
@Override
public void changed(ProgressEvent event) {
loading = true;
}
});
}
public boolean loadPage(String url) {
Display display = ... // Get the display from the UI or the widget
boolean set = browser.setUrl(url); // URL content loading is asynchronous
loading = true;
while(loading) { // Add synchronous behavior: wait till it finishes loading
if(!display.readAndDispatch()) {
display.sleep();
}
}
return set;
}