This guide describes the navigation events, and shows how to load URLs and files, filter navigation requests, work with navigation history, etc.

Loading URL

To navigate to a resource identified by a URL you can use one of the following methods:

  • Navigation.loadUrl(String url)
  • Navigation.loadUrl(LoadUrlParams params)

The following example shows how to navigate to https://www.google.com using the Navigation.loadUrl(String) method:

Navigation navigation = browser.getNavigation();
navigation.loadUrl("https://www.google.com");

The code below requests navigation to the given resource and exits immediately. It does not wait until the resource is loaded completely.

If you need to block the current thread execution until the resource is loaded completely, use the Navigation.loadUrlAndWait(String url, int timeoutInSeconds) method:

navigation.loadUrlAndWait("https://www.google.com", 45);

This method blocks the current thread execution until the main frame of the resource is loaded completely or until the given 45 seconds timeout is reached.

If navigation fails, the NavigationException exception will be thrown.

If the resource has not been loaded within a timeout, the TimeoutException exception will be thrown.

Loading URL with POST

To load a web page by its URL and send POST data, use the Navigation.loadUrl(LoadUrlParams) method. The following code demonstrates how to load URL and send POST data in different formats using extra headers.

You can send a web form data in the key=value format to a web server:

navigation.loadUrl(LoadUrlParams.newBuilder()
        .setUrl("https://www.google.com")
        // The POST data in the key=value format.
        // If you don't specify extra headers, then the extra headers
        // will be set to "Content-Type: application/x-www-form-urlencoded\n"
        .setPostData("myKey=myValue&myKey2=myValue2")
        .build());

If you want to send some plain text, then you must add the extra headers that tell the web server it is a plain text:

navigation.loadUrl(LoadUrlParams.newBuilder()
        .setUrl("https://www.google.com")
        // The POST data in the plain text format.
        .setPostData("Some Text...")
        // The Content-Type header that tells a web server
        // we sent POST data in the text/plain format.
        .addHttpHeaders(HttpHeader.newBuilder()
                .setName("Content-Type")
                .setValue("text/plain")
                .build())
        .build());

You can send any data of various types. The only requirement is that you must specify its Content-Type. Here’s how to send JSON data:

navigation.loadUrl(LoadUrlParams.newBuilder()
        .setUrl("https://www.google.com")
        // The POST data in the JSON format.
        .setPostData("{\"title\":\"Hello\"}")
        // The Content-Type header that tells a web server
        // we sent POST data in the application/json format.
        .addHttpHeaders(HttpHeader.newBuilder()
                .setName("Content-Type")
                .setValue("application/json")
                .build())
        .build());

Loading File

You can use the same methods to load HTML files from the local file system. You just need to provide an absolute path to the HTML file instead of a URL.

For example:

navigation.loadUrl(new File("index.html").getAbsolutePath());

Loading Data

You can navigate Frame to the data with specified MIME type, document Base URL (for text/html only) and optional text encoding.

For example:

frame.loadData(LoadDataParams.newBuilder()
        .setData("<html><body>Hello</body></html>")
        .setBaseUrl("<url>")
        .setTextEncoding("UTF-8")
        .setMimeType(MimeType.newBuilder()
                .setValue("text/html")
                .build())
        .build());

Loading HTML

You can navigate Frame to the data that represents an HTML document with the text/html MIME type.

You can load only HTML string:

frame.loadHtml("<html><body>HTML Text</body></html>");

Or you can provide additional options such as Base URL when loading HTML:

frame.loadHtml(LoadHtmlParams.newBuilder()
        .setHtml("<html><body>HTML Text</body></html>")
        .setBaseUrl("<url>")
        .build());

Reloading

There are several options to reload the currently loaded web page:

Reload using HTTP cache:

navigation.reload();

Reload ignoring HTTP cache:

navigation.reloadIgnoringCache();

Reload using HTTP cache and check for repost:

navigation.reloadAndCheckForRepost();

Reload ignoring HTTP cache and check for repost:

navigation.reloadIgnoringCacheAndCheckForRepost();

Stopping

Use the Navigation.stop() method to cancel any pending navigation or download operation, and stop any dynamic page elements, such as background sounds and animations. For example:

navigation.stop();

Back & Forward

JxBrowser allows working with the navigation back-forward history list.

When you create a Browser instance it navigates to the about:blank web page by default, so there is always one entry in the navigation back-forward list.

To load the previous location in the back-forward list use the following approach:

if (navigation.canGoBack()) {
    navigation.goBack();
}

To load the next location in the back-forward list use:

if (navigation.canGoForward()) {
    navigation.goForward();
}

To navigate to the entry at a specific index in the back-forward list use:

if (index >=0 && index < navigation.getEntryCount()) {
    navigation.goToIndex(index);
}

You can go through the back-forward list and get the details about every navigation entry:

int entryCount = navigation.getEntryCount();
for (int index = 0; index < entryCount; index++) {
    navigation.getEntryAtIndex(index).ifPresent(navigationEntry -> {
        System.out.println("URL: " + navigationEntry.getUrl());
        System.out.println("Title: " + navigationEntry.getTitle());
    });
}

You can modify the back-forward list by removing the entries:

// Returns the number of entries in the back/forward list.
int entryCount = navigation.getEntryCount();
// Remove navigation entries at index.
for (int i = entryCount - 2; i >= 0; i--) {
    boolean success = navigation.removeEntryAtIndex(i);
    System.out.println("Navigation entry at index " + i +
            " has been removed successfully? " + success);
}

Filtering URLs

You can decide whether a web page should be loaded. By default all URLs are allowed to be loaded.

The following code demonstrates how to cancel navigation to all URLs that start with https://www.google:

browser.set(LoadRequestCallback.class, (params, callback) -> {
    if (params.getUrl().startsWith("https://www.google")) {
        // Cancel loading URLs that start with "https://www.google"
        callback.cancel();
    } else {
        callback.load();
    }
});

Filtering Resources

Using the LoadResourceCallback callback you can determine whether the resources such as HTML, image, JavaScript or CSS file, favicon, etc. should be loaded. By default all resources are loaded. To modify the default behavior you must register your own callback implementation where you decide what resources should be canceled or loaded.

The following example demonstrates how to suppress all images:

NetworkService networkService = engine.getNetworkService();
networkService.set(LoadResourceCallback.class, (params, callback) -> {
    if (params.getResourceType() != ResourceType.RESOURCE_TYPE_IMAGE) {
        callback.cancel();
    } else {
        callback.load();
    }
});

Swipe Navigation

By default left/right swipe on touch screens navigates back/forward. To disable this default behavior use an appropriate option when constructing the Engine as shown in the following example:

Engine engine = Engine.newInstance(EngineOptions.newBuilder()
        .setOverscrollHistoryNavigation(OverscrollOptions.DISABLE)
        ...
        .build());

Loading a web page is a complex process during which different navigation events are fired. The following diagram shows the order in which the navigation events might be fired when loading a web page: Navigation Events Flow

Load Started

To get notifications when content loading has started please use the LoadStarted event. For example:

browser.on(LoadStarted.class, event -> {});

This event corresponds to the moment when the spinner of the tab starts spinning.

Load Finished

To get notifications when content loading has finished please use the LoadFinished event. For example:

browser.on(LoadFinished.class, event -> {});

This event corresponds to the moment when the spinner of the tab stops spinning.

To get notifications when navigation has started please use the NavigationStarted event. For example:

browser.on(NavigationStarted.class, event -> {
    String url = event.getUrl();
    // Indicates whether the navigation will be performed
    // in the scope of the same document.
    boolean isSameDocument = event.getIsSameDocument();
});

To get notifications when navigation has stopped please use the NavigationStopped event. For example:

browser.on(NavigationStopped.class, event -> {});

This event is fired when navigation is stopped via the Navigation.stop() method.

To get notifications when navigation has been redirected to a new URL please use the NavigationRedirected event. For example:

browser.on(NavigationRedirected.class, event -> {
    // The navigation redirect URL.
    String url = event.getUrl();
});

To get notifications when navigation has finished please use the NavigationFinished event. For example:

browser.on(NavigationFinished.class, event -> {
    String url = event.getUrl();
    Frame.with(event.getFrameId()).ifPresent(frame -> {});
    boolean hasCommitted = event.getHasCommitted();
    boolean isSameDocument = event.getIsSameDocument();
    boolean isErrorPage = event.getIsErrorPage();
    if (isErrorPage) {
        NetError errorCode = event.getErrorCode();
    }
});

This event is fired when navigation is committed, aborted, or replaced by a new one. To know if the navigation has committed, use NavigationFinished.getHasCommitted(); use NavigationFinished.getIsErrorPage() to know if the navigation resulted in an error page.

If the event is called because the navigation committed, the document load will still be ongoing.

The event is fired by same-document (in the scope of the same document) navigations, such as fragment navigations or window.history.pushState()/window.history.replaceState(), which will not result in a document change. Please use NavigationFinished.getIsSameDocument() to check if it is a same-document navigation.

Frame Load Finished

To get notifications when content loading in the Frame has finished please use the FrameLoadFinished event. For example:

browser.on(FrameLoadFinished.class, event -> {
    String url = event.getValidatedUrl();
    Frame.with(event.getFrameId()).ifPresent(frame -> {});
});

This event corresponds to the moment when the content in the Frame has been loaded completely.

Frame Document Load Finished

To get notifications when the document loading in the Frame has finished please use the FrameDocumentLoadFinished event. For example:

browser.on(FrameDocumentLoadFinished.class, event ->
        Frame.with(event.getFrameId()).ifPresent(frame -> {}));

At this point, deferred scripts were executed, and the content scripts marked “document_end” get injected into the frame.

Go Top