在WebView内加载html文件并直接跳转到html内的id [英] load a html File inside an WebView and jump direct to an id inside the html

查看:92
本文介绍了在WebView内加载html文件并直接跳转到html内的id的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在WebView中加载html文件,然后直接跳转到html中的id.

I want to load a html File inside an WebView and jump direct to an id inside the html.

import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.paint.Color;
import javafx.scene.web.WebView;
import javafx.stage.Stage;

public class HelpViewer extends Application {
   public static void main(String[] args) {launch(args);}

   @Override
   public void start(Stage stage) {
      WebView webview = new WebView();
webview.getEngine().load(HelpViewer.class.getResource("HelpViewer.html").toExternalForm());

      // does not work
      //     webview.getEngine().load(MapViewer.class.getResource("MapViewer.html#Headline2").toExternalForm());

      // does not work
      // webview.goto("#Headline2");

      stage.setScene(new Scene(webview, 200, 600, Color.WHITE));
      stage.show();
   }
}

我找不到从Code导航到ID的方法.

I couldn't find a Way to navigate to an id from Code.

html文件:

html-File:

<h1><a id="Headline1">Headline 1</a></h1> 
<p>GOTO <a href="#Headline2">Headline 2</a></p>

<p>Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet. Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet.</p>

<h1><a id="Headline2">Headline 2</a></h1>
<p>GOTO <a href="#Headline1">Headline 1</a></p>

</body></html>

推荐答案

The API about WebEngine says:

评估JavaScript表达式

可以在以下环境中执行任意JavaScript代码 当前页面使用executeScript(java.lang.String)方法.为了 例如:

It is possible to execute arbitrary JavaScript code in the context of the current page using the executeScript(java.lang.String) method. For example:

webEngine.executeScript("history.back()");

因此,您可以使用

Hence, you can execute document.getElementById('id').scrollIntoView(); with executeScript() after adding a listener to check the state of the LoadWorker (read within the API about WebEngine the part Loading Web Pages as well):

WebEngine webEngine = webview.getEngine();

webEngine.getLoadWorker().stateProperty().addListener((ov, oldState, newState) -> {
   if (newState == Worker.State.SUCCEEDED) {
      webEngine.executeScript("document.getElementById('id').scrollIntoView();");
   }
});

这篇关于在WebView内加载html文件并直接跳转到html内的id的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆