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()));
browser.mainFrame().ifPresent { frame -> println(frame.html()) }

Accessing selection

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

Java
Kotlin
String 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
String selectionAsText = frame.selectionAsText();
val selectionAsText = frame.selectionAsText()

Finding text

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

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

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

Java
Kotlin
TextFinder 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.
        int numberOfMatches = findResult.numberOfMatches();
    }
});
// 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.
        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 that it is not being loaded before saving a web page. It is recommended to completely loaded the web page and only then save 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
Path path = createTempDir("web_page");
Path file = path.resolve("target.html");
Path directory = path.resolve("resources");
if (browser.saveWebPage(file, directory, SavePageType.COMPLETE_HTML)) {
    // The saving process has been initialized successfully.
} else {
    // The saving process has been 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 been 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.
Engine engine = Engine.newInstance(
        EngineOptions.newBuilder(HARDWARE_ACCELERATED).build());
Browser 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://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();
// Creating and running Chromium engine.
val engine = Engine.newInstance(
    EngineOptions.newBuilder(HARDWARE_ACCELERATED).build())
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://www.google.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.
Bitmap bitmap = browser.bitmap();

// Convert the bitmap to java.awt.image.BufferedImage.
BufferedImage 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
import com.teamdev.jxbrowser.view.javafx.graphics.BitmapImage;
...

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

// Convert the bitmap to javafx.scene.image.Image.
Image image = BitmapImage.toToolkit(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"));
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.
Bitmap bitmap = browser.bitmap();

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

// Save the image to a PNG file.
ImageLoader 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.

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.

Default encoding

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

Java
Kotlin
browser.settings().defaultEncoding("UTF-8");
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:

Java
Kotlin
browser.settings().disableJavaScript();
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:

Java
Kotlin
browser.settings().disableImages();
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:

Java
Kotlin
browser.settings().disablePlugins();
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:

Java
Kotlin
browser.settings().disableLocalStorage();
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:

Java
Kotlin
browser.settings().hideScrollbars();
browser.settings().hideScrollbars()

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

Display mode

The display-mode CSS media feature defines how the web app is displayed in a regular browser, in the fullscreen mode, as a standalone app, or in other ways.

To configure the display-mode for the Browser, use this code:

Java
Kotlin
browser.settings().displayMode(DisplayMode.FULLSCREEN);
browser.settings().displayMode(DisplayMode.FULLSCREEN)

This setting changes the value in CSS and affects which CSS rules apply. But note, that this setting doesn’t change how the browser display the web page.

In other words, the code above will activate CSS under @media (display-mode: fullscreen) media query, but will not switch the browser into the fullscreen mode.

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 = frame.sessionStorage()
val 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:

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

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

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