How can I get the document height for a webview control in JavaFx?
Asked
Active
Viewed 4,131 times
4
-
Java and Javascript are quite different. Also, please expand your question, perhaps with what you have tried. – Lee Taylor Apr 01 '13 at 00:50
-
I have an webview control and I want to set it's height relative at the document height. – John Smith Apr 01 '13 at 00:54
-
Please update your question by clicking edit. Your comment merely rearranges the words in your original question! – Lee Taylor Apr 01 '13 at 00:57
2 Answers
5
You can get the height of a document displayed in a WebView using the following call:
webView.getEngine().executeScript(
"window.getComputedStyle(document.body, null).getPropertyValue('height')"
);
A complete app to demonstrate the call usage:
import javafx.application.Application;
import javafx.beans.value.*;
import javafx.scene.Scene;
import javafx.scene.web.*;
import javafx.stage.Stage;
import org.w3c.dom.Document;
public class WebViewHeight extends Application {
@Override public void start(Stage primaryStage) {
final WebView webView = new WebView();
final WebEngine engine = webView.getEngine();
engine.load("http://docs.oracle.com/javafx/2/get_started/animation.htm");
engine.documentProperty().addListener(new ChangeListener<Document>() {
@Override public void changed(ObservableValue<? extends Document> prop, Document oldDoc, Document newDoc) {
String heightText = webView.getEngine().executeScript(
"window.getComputedStyle(document.body, null).getPropertyValue('height')"
).toString();
double height = Double.valueOf(heightText.replace("px", ""));
System.out.println(height);
}
});
primaryStage.setScene(new Scene(webView));
primaryStage.show();
}
public static void main(String[] args) { launch(args); }
}
Source of the above answer: Oracle JavaFX forums WebView configuration thread.
Related issue tracker request for a Java based API for a related feature:

jewelsea
- 150,031
- 14
- 366
- 406
-
It works, however the result is not true. I measured via pixel line, the height was about 480px and the code returned 414px. – Jun 05 '15 at 05:54
-
Thanks for your anser. This is a bit late reply. Your example is running. However I have a webview, which is embedded in an `TableCell`. Here the result is always 0 px (Close to: https://stackoverflow.com/questions/22334983/java-fx-tableview-display-simple-html/22335276#22335276) any idea on how to fix this? – BerndGit Mar 17 '17 at 12:13
-
Kindly see: https://stackoverflow.com/questions/42856471/workaround-for-rt-25005-automatic-preferred-sizing-of-webview for more specific question including running example. – BerndGit Mar 17 '17 at 14:24
0
This is what you're looking for:
Double.parseDouble(webView.getEngine().executeScript("document.height").toString())

Someone
- 216
- 3
- 8