JxBrowser displays the content of various types, e.g. images, video, PDF, Flash etc, but in most cases you will display the HTML content of a web page. This guide shows how to access the content of a web page, get the currently selected text, find some text on a web page, save the web page as a file or a set of files, etc.

Content Size

By default the Browser size is empty. Many web pages rely on this size and require it not to be empty. Otherwise, the layout of the DOM document might not be parsed and displayed at all.

If you do not need to display the content of a loaded web page, but the page should “think” it is loaded in a Browser with a non-empty size, then please set the size programmatically using the Browser.resize(Size) method.

Accessing HTML

To get a string that represents HTML of a Frame please use the Frame.html() method.

Please call this method only when the Frame is loaded completely. Otherwise you may receive incomplete HTML or an empty string.

The following example demonstrates how to print HTML of the currently loaded main Frame:

browser.mainFrame().ifPresent(frame -> System.out.println(frame.html()));

Accessing Selection

To get selection on the currently loaded Frame as HTML use the Frame.selectionAsHtml() method:

String selectionAsHtml = frame.selectionAsHtml();

If you only need the selected text without the selection’s HTML, please use the Frame.selectionAsText() method as described in the example below:

String selectionAsText = frame.selectionAsText();

Finding Text

JxBrowser allows you to find text on the currently loaded web page and highlight all the matches.

JxBrowser searches text only through the visible content of the loaded web pages which have non-empty size.

To perform the search on the currently loaded web page use the TextFinder class:

TextFinder textFinder = browser.textFinder();

The following example demonstrates how to find the “text” on the currently loaded web page with the specified search parameters, and wait until the search has been completed:

// Find "text" in the currently loaded web page with the given params.
textFinder.find("text", FindOptions.newBuilder()
        .matchCase(true)
        .build(), findResult -> {
    // Check if the text search has been finished.
    if (findResult.isSearching()) {
        // The Text Finder is still searching the text.
        // It's recommended to wait until the search is finished.
    } else {
        // Text search has been finished, so get total the number of matches.
        int numberOfMatches = findResult.numberOfMatches();
    }
});

The search matches are highlighted as follows:

Find Text Highlights

To clear the highlighted search results on a web page and cancel the search please use the TextFinder.stopFindingAndClearSelection() or TextFinder.stopFindingAndKeepSelection() method.

For example:

textFinder.stopFindingAndClearSelection();

Saving Web Page

JxBrowser allows you to save a web page as a file or a set of files.

It is done via the Browser.saveWebPage(Path, Path, SavePageType) method, which accepts three parameters:

  • A string with a name of the target file.
  • A string with the directory path to save page resources.
  • A type of the save operation (SavePageType).

For example:

Path path = createTempDir("save_web_page");
Path file = path.resolve("index.html");
Path directory = path.resolve("resources_dir");
if (browser.saveWebPage(file, directory, SavePageType.COMPLETE_HTML)) {
    System.out.println("The web page has been saved to " + file);
} else {
    System.err.println("Failed to save the web page to " + file);
}

Taking Bitmap of a Web Page

The library allows you to take a bitmap that contains the pixels of the currently loaded web page. The bitmap size equals to the size of the Browser instance where the web page is loaded.

In order to get an image of a web page we recommend that you perform the following actions:

  1. Resize the Browser instance to the required dimension (e.g. 500x500).
  2. Load a web page and wait until the main frame of the web page is loaded completely.
  3. Take the bitmap of the currently loaded web page.

The following example demonstrates how to do that:

// Creating and running Chromium engine.
Engine engine = Engine.newInstance(
        EngineOptions.newBuilder(HARDWARE_ACCELERATED).build());
Browser browser = engine.newBrowser();

// Resize browser to the required dimension.
browser.resize(500, 500);

// Load the required web page and wait until it is loaded completely.
browser.navigation().loadUrlAndWait("https://www.google.com");

// Take the bitmap of the currently loaded web page. Its size will be 
// equal to the current browser's size.
Bitmap bitmap = browser.bitmap();

The received bitmap you can convert to a Java AWT java.awt.image.BufferedImage or JavaFX javafx.scene.image.Image for further manipulations (e.g. saving to a PNG file).

AWT BufferedImage

The following code demonstrates how to convert Bitmap to java.awt.image.BufferedImage and save it to the bitmap.png file on the local file system:

// Convert the bitmap to java.awt.image.BufferedImage
BufferedImage image = 
        com.teamdev.jxbrowser.view.swing.BitmapUtil.toBufferedImage(bitmap);
// Save the image to a PNG file
ImageIO.write(image, "PNG", new File("bitmap.png"));

JavaFX Image

The following code demonstrates how to convert Bitmap to javafx.scene.image.Image and save it to the bitmap.png file on the local file system:

// Convert the bitmap to javafx.scene.image.Image
Image image = com.teamdev.jxbrowser.view.javafx.BitmapUtil.toImage(bitmap);
// Convert javafx.scene.image.Image to java.awt.image.BufferedImage
BufferedImage bufferedImage = SwingFXUtils.fromFXImage(image, null);
// Save the image to a PNG file
ImageIO.write(bufferedImage, "PNG", new File("bitmap.png"));

Settings

Using BrowserSettings you can configure different content settings for a single Browser instance. You can disable images, plugins, JavaScript, local storage, application cache, allow running insecure content or allow JavaScript access clipboard, etc. The list of supported settings you can find in the API specification.

Default Encoding

To configure the default text encoding on a web page use:

browser.settings().defaultEncoding("UTF-8");

JavaScript

By default, JavaScript is enabled on a web page. If you need to disable JavaScript, then use the following:

browser.settings().disableJavaScript();

Images

If you do not need to display images on a web page to reduce the network traffic, then you can disable images:

browser.settings().disableImages();

Plugins

You can filter the installed plugins, but if you just need to disable all plugins on a web page, then use the following approach:

browser.settings().disablePlugins();

Local Storage

The local WebStorage is enabled by default. In order to disable it and prevent JavaScript from storing date in the local storage, use the following setting:

browser.settings().disableLocalStorage();

Scrollbars

You might want to hide scrollbars on a web page when taking bitmap of a web page or inside Kiosk applications. In this case use the following setting:

browser.settings().hideScrollbars();

Once you call this method, the web pages loaded in the Browser instance will not display scrollbars anymore.

Web Storage

JxBrowser allows you to access and work with the JavaScript Web Storage that provide mechanisms by which browsers can store key/value pairs, in a much more intuitive fashion than using cookies.

There are two types of the Web Storage:

  • sessionStorage maintains a separate storage area for each given origin that is available for the duration of the page session.
  • localStorage does the same thing, but persists even when the browser is closed and reopened.

To access the session and local Web Storage please use the following approach:

WebStorage sessionStorage = frame.sessionStorage();
WebStorage localStorage = frame.localStorage();

The localStorage can be disabled. In this case the WebStorage methods will throw the WebStorageSecurityException error.

The following example demonstrates how to put an item to the localStorage using JxBrowser WebStorage API:

frame.localStorage().putItem("Name", "Tom");

You can access the inserted item in JavaScript using the following code:

window.localStorage.getItem('Name'); // <- Returns "Tom"
Go Top