简体   繁体   中英

JavaFX 2 WebView URL Listener

When using a JavaFX (2.2) WebView, is there a way to listen to and handle url's within java code?

For example: I'm loading a local HTML file to my WebView with webEngine.loadContent(html). The HTML contains resources like

<script src="local:my-script.js"></script>
<img src="cms:1234.png"/>

which is also a local file and should be provided from the java application. So I want to register a listener that could handle requests from the page.

Edit: The resource data that is loaded within the HTML page comes from a content-managemant-system so using relative paths is not working.

Create your own URL protocol handler and install it using:

URL.setURLStreamHandlerFactory(new HandlerFactory());

A New Era for Java URL Protocol Handlers article provides detailed instructions for creating the handler.

WebView can make use of your custom protocol to load your content.

The easiest way for you would be substituting local: resource with runtime value in html right before loading it. Eg:

public class WebViewLocal extends Application {
    @Override
    public void start(Stage primaryStage) {
        String st = "<html><head><title>X</title>"
                + "</head><body><img src='local:1.jpg'/>"
                + "</body></html>";
        System.out.println(st);
        primaryStage.setScene(new Scene(loadHtml(st), 400, 400));
        primaryStage.show();
    }

    public WebView loadHtml(String html) {
        html = html.replace("local:", getClass().getResource(".").toString());
        WebView view = new WebView();
        view.getEngine().loadContent(html);
        return view;
    }

    public static void main(String[] args) { launch(); }
}

NB: This is working sample, just put 1.jpg image at the same place as this file.

If you really want to work with java class from javascript you can use "JavaFX to JavaScript bridge" feature. Take a look at tutorial here: https://blogs.oracle.com/javafx/entry/communicating_between_javascript_and_javafx

If you load your html-file locally, you can simply use relative paths:

This is an example, which load html, with relative scripts. http://code.google.com/p/jfx-gap/source/browse/src/main/java/com/googlecode/jfxgap/JFXGap.java

The trick schould be the relative path inside the html.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM