Hi. I need to take a snapshot of a web page that was just loaded with WebView. Immediately after the WebEngine LoadWorker's notification fires, I call WebView.snapshot(). Unfortunately, the page has loaded, but it doesn't appear to be rendered into the Scene at the instant I take the snapshot. After a full day of trial-and-error (mostly error) I managed to get it to work by sleeping for 50ms before taking the snapshot. This as it turns out is a royal pain in practice because WebView wants to be called only from the main JavaFX Application thread, and I appears I to need to get out of the present JavaFX Application thread (from the notifier) in order for WebView to do it's rendering thing.
Is there any way to find out when a newly loaded page has actually finished rendering into WebView? Yes I know there is no such thing as finished since there could be animations going. But I would at least like to know when the newly loaded DOM has been rendered "for the first time". Or is there some other way to do what I am trying to accomplish without the magic sleep, and without so many ugly lines of code?
Thread snapshotThread = new Thread(new Runnable() {
@Override
public void run() {
try {
Thread.sleep(50); // !!! Here is the magic
} catch (InterruptedException e1) {
throw new IllegalStateException(e1);
}
final Ref<Image> ref = new Ref<Image>(null);
final CountDownLatch imageLatch = new CountDownLatch(1);
Platform.runLater(new Runnable() {
@Override
public void run() {
SnapshotParameters params = new SnapshotParameters();
ref.set(webView.snapshot(params, null));
imageLatch.countDown();
}
});
try {
imageLatch.await();
} catch (InterruptedException e2) {
throw new IllegalStateException(e2);
}
ByteArrayOutputStream baos = new ByteArrayOutputStream();
try {
ImageIO.write(SwingFXUtils.fromFXImage(ref.get(), null), "png", baos);
} catch (IOException e) {
throw new IllegalStateException(e);
}
String name = webView.getEngine().getLocation() + " " + (new Date()).toString();
RegisteredImage ra = new RegisteredImage(key, name, "image/png", baos.toByteArray());
ImageRegistrar.register(ra);
}
});
snapshotThread.start();