JavaFX webview,获取文档高度

JavaFX webview, get document height

本文关键字:文档 高度 获取 webview JavaFX      更新时间:2023-09-26

如何在JavaFx中获得webview控件的文档高度?

您可以使用以下调用获取WebView中显示的文档的高度:

webView.getEngine().executeScript(
    "window.getComputedStyle(document.body, null).getPropertyValue('height')"
);

一个完整的应用程序来演示呼叫使用情况:

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); }
}

以上答案的来源:Oracle JavaFX论坛的WebView配置线程。


相关问题跟踪器请求为相关特性提供基于Java的API:

RT-25005 WebView自动选择大小

这就是你要找的:

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