Skip to content Skip to sidebar Skip to footer

Javafx Webview, Get Document Height

How can I get the document height for a webview control in JavaFx?

Solution 1:

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;

publicclassWebViewHeightextendsApplication {
  @Overridepublicvoidstart(Stage primaryStage) {
    finalWebViewwebView=newWebView();
    finalWebEngineengine= webView.getEngine();
    engine.load("http://docs.oracle.com/javafx/2/get_started/animation.htm");
    engine.documentProperty().addListener(newChangeListener<Document>() {
      @Overridepublicvoidchanged(ObservableValue<? extends Document> prop, Document oldDoc, Document newDoc) {
        StringheightText= webView.getEngine().executeScript(
          "window.getComputedStyle(document.body, null).getPropertyValue('height')"
        ).toString();
        doubleheight= Double.valueOf(heightText.replace("px", ""));    

        System.out.println(height);
      }
    });
    primaryStage.setScene(newScene(webView));
    primaryStage.show();
  }

  publicstaticvoidmain(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:

RT-25005 Automatic preferred sizing of WebView.

Solution 2:

This is what you're looking for:

Double.parseDouble(webView.getEngine().executeScript("document.height").toString())

Post a Comment for "Javafx Webview, Get Document Height"