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. E.g.:
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(); }
}
N.B.: 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 love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With