Nicolai Parlog edited this page May 1, 2015 · 6 revisions

This feature is concerned with adding a listener to JavaFX' WebView which gets called when the user interacts with hyperlinks.

The feature's concept is described below before examples demonstrates its use. A self-contained demo showcases it in action. There is also an explanatory comment on the package org.codefx.libfx.control.webview.


JavaFX contains a WebView, which is basically a small browser. Unfortunately it does not provide an easy way to add a listener which gets called when the user interacts with hyperlinks. It is necessary to wriggle into the control's current DOM document and work on the naked DOM classes.

This feature remedies the situation. It provides an interface WebViewHyperlinkListener, which is very similar to Swing's HyperlinkListener and also processes a HyperlinkEvent. The only difference is that its return value can prevent the WebView from further processing the event.

Listeners are added by calling the corresponding methods on the utility class WebViews. They are aware of ListenerHandles and return such instances.


Let's create a listener which prints the hyperlink event to the console:

WebViewHyperlinkListener eventPrintingListener = event -> {
	return false;
WebViews.addHyperlinkListener(webView, eventPrintingListener);

If a listener should only be called for one event type, a filter can be used when adding it:

WebViewHyperlinkListener activationCancelingListener =
		webView, activationCancelingListener,

In order to detach and reattach a listener the returned listener handle can be used:

WebViewHyperlinkListenerHandle printingListener = 
		WebViews.addHyperlinkListener(webView, this::printEvent);

// code...


// code...