List icon Contents

Content

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:

Java
Kotlin

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

println(browser.mainFrame?.html)

Accessing selection

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

Java
Kotlin

var selectionAsHtml = frame.selectionAsHtml();

val 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:

Java
Kotlin

var selectionAsText = frame.selectionAsText();

val selectionAsText = frame.selectionAsText()

Finding text

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

JxBrowser searches text only through the visible part of the loaded content that has non-empty size.

To perform the search on the currently loaded content use TextFinder:

Java
Kotlin

var textFinder = browser.textFinder();

val textFinder = browser.textFinder

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

Java
Kotlin

// 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.
        var numberOfMatches = findResult.numberOfMatches();
    }
});

// Find "text" in the currently loaded web page with the given params.
val options = FindOptions(matchCase = true)
textFinder.find("text", options) { 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.
        val numberOfMatches = findResult.numberOfMatches()
    }
}

The search matches are highlighted as follows:

Find Text Highlights

Canceling search

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:

Java
Kotlin

textFinder.stopFindingAndClearSelection();

textFinder.stopFindingAndClearSelection()

Saving web page

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

Use Browser.saveWebPage(Path, Path, SavePageType) with the following parameters:

  • path to the target file
  • path to the directory where the page resources will be saved
  • type of the save operation

Please make sure to fully load the web page before saving it.

This method initiates the saving process and returns immediately. So, there’s no guarantee that the web page will be saved completely by the time the method returns. To find out when the web page is saved completely, check the existence of the target file using Java NIO API.

For example:

Java
Kotlin

var path = createTempDir("web_page");
var file = path.resolve("target.html");
var directory = path.resolve("resources");
if (browser.saveWebPage(file, directory, SavePageType.COMPLETE_HTML)) {
    // The saving process has been initialized successfully.
} else {
    // The saving process has failed.
}

val path = createTempDirectory("web_page")
val file = path.resolve("target.html")
val directory = path.resolve("resources")
if (browser.saveWebPage(file, directory, SavePageType.COMPLETE_HTML)) {
    // The saving process has been initialized successfully.
} else {
    // The saving process has failed.
}

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. 1024х768).
  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:

Java
Kotlin

// Creating and running Chromium engine.
var engine = Engine.newInstance(HARDWARE_ACCELERATED);
var browser = engine.newBrowser();

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

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

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

// Creating and running Chromium engine.
val engine = Engine(RenderingMode.HARDWARE_ACCELERATED)
val browser = engine.newBrowser()

// Resize browser to the required dimension.
browser.resize(1024, 768)

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

// Take the bitmap of the currently loaded web page. Its size will be
// equal to the current browser's size.
val 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:

Java
Kotlin

import com.teamdev.jxbrowser.view.swing.graphics.BitmapImage;
...
// Take the bitmap.
var bitmap = browser.bitmap();

// Convert the bitmap to java.awt.image.BufferedImage.
var image = BitmapImage.toToolkit(bitmap);

// Save the image to a PNG file.
ImageIO.write(image, "PNG", new File("bitmap.png"));

import com.teamdev.jxbrowser.view.swing.graphics.BitmapImage
...
// Take the bitmap.
val bitmap = browser.bitmap()

// Convert the bitmap to java.awt.image.BufferedImage.
val image = BitmapImage.toToolkit(bitmap)

// Save the image to a PNG file.
ImageIO.write(image, "PNG", File("bitmap.png"))

See complete example.

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:

Java
Kotlin

// Take the bitmap.
var bitmap = browser.bitmap();

// Convert the bitmap to javafx.scene.image.Image.
var image = BitmapImage.toToolkit(bitmap);

// Convert javafx.scene.image.Image to java.awt.image.BufferedImage.
var bufferedImage = SwingFXUtils.fromFXImage(image, null);

// Save the image to a PNG file.
ImageIO.write(bufferedImage, "PNG", new File("bitmap.png"));

import com.teamdev.jxbrowser.view.javafx.graphics.BitmapImage
...
// Take the bitmap.
val bitmap = browser.bitmap

// Convert the bitmap to javafx.scene.image.Image.
val image = BitmapImage.toToolkit(bitmap)

// Convert javafx.scene.image.Image to java.awt.image.BufferedImage.
val bufferedImage = SwingFXUtils.fromFXImage(image, null)

// Save the image to a PNG file.
ImageIO.write(bufferedImage, "PNG", File("bitmap.png"))

See complete example.

SWT Image

To convert Bitmap to ImageData and save it to the bitmap.png file on a local file system use the following approach:

Java
Kotlin

import com.teamdev.jxbrowser.view.swt.graphics.BitmapImage;
...
// Take the bitmap.
var bitmap = browser.bitmap();

// Convert the bitmap to org.eclipse.swt.graphics.Image.
var image = BitmapImage.toToolkit(display, bitmap);

// Save the image to a PNG file.
var loader = new ImageLoader();
loader.data = new ImageData[]{image.getImageData()};
loader.save("bitmap.png", SWT.IMAGE_PNG);

import com.teamdev.jxbrowser.view.swt.graphics.BitmapImage
...
// Take the bitmap.
val bitmap = browser.bitmap

// Convert the bitmap to org.eclipse.swt.graphics.Image.
val image = BitmapImage.toToolkit(display, bitmap)

// Save the image to a PNG file.
val loader = ImageLoader()
loader.data = arrayOf(image.imageData)
loader.save("bitmap.png", SWT.IMAGE_PNG)

See complete example.

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:

Java
Kotlin

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

val sessionStorage: WebStorage = frame.sessionStorage
val localStorage: WebStorage = frame.localStorage

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

To add a new item to the storage, use the putItem(String, String) method:

Java
Kotlin

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

localStorage["Name"] = "李白"

To read an item from the storage, use the item(String) method:

Java
Kotlin

var name = localStorage.item("Name");

val name = localStorage["Name"]

To check if the item exists in the storage, pass the item key to the has(String) method:

Java
Kotlin

var hasName = localStorage.contains("Name");

val hasName = localStorage.contains("Name")

To read all items from the storage, use the key(Integer) and length() methods to iterate over the stored items:

Java
Kotlin

var storageLength = localStorage.length();
for (int i = 0; i < storageLength; i++) {
    int index = i;
    localStorage.key(i).ifPresent(item -> {
        System.out.println("Item at [" + index + "] is " + item);
    });
}

val storageLength = localStorage.length
for (i in 0 until storageLength) {
    localStorage.key(i).ifPresent { item ->
        println("Item at [$i] is $item")
    }
}

To remove a single item from the storage, use the removeItem(String) method:

Java
Kotlin

localStorage.removeItem("Name");

localStorage.removeItem("Name")

To remove all items from the storage in one call, use the clear() method:

Java
Kotlin

localStorage.clear();

localStorage.clear()