JavaFX WebView: snippets

Today I present a few snippets around JavaFX WebView that I use in The Console:

  • load style sheet
  • set style or class of element
  • scroll page to the bottom
  • check whether the page is scrolled down to the bottom
  • handle adding DOM elements while web engine loads
  • remove some elements from document
  • style scrollbar in the document

Load style sheet

Set element style or class

Scroll to the bottom

Since HTML page is not a domain of JavaFX but our WebView, simply scrolling down to the bottom of page is a matter of internal WebView scrollbar rather than any JavaFX control. That’s why we have to handle this situation with JavaScript.

Is it scrolled down?

In The Console I scroll down the page when new text line appears. But sometimes it’s a bit frustrating when you want to read certain lines and now ones keep being added. That’s why I want to check whether page is scrolled down to the bottom or not. If the page wasn’t scrolled down before adding a text entry then I don’t scroll it down automatically after adding the text entry. JavaScript comes again.

Handle adding data to HTML during loading

WebView consists of WebKit engine which is loaded asynchronously. In The Console I write initialization logs to console too, so I need it as quick as possible. Instead of waiting for initialization I create tasks and push them to the queue. When succeeds loading then I launch all tasks.

And here’s a method I used for appending text entries to the console, even if it’s still not loaded – by queuing them as tasks.

Remove some elements

Here’s another job that needs dealing with a document. But this time, instead of injecting JavaScript code, we’re going to use the power of org.w3c.dom.

entries  is a custom collection that contains entryNode s.

Style WebView scrollbar

Styling again but this time it’s a little harder. Styling JavaFX scrollbars is easy but it’s a little harder to find out how to style scrollbars inside WebView’s document. Here’s what I used for The Console.