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.navigation();
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("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"
        .postData("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("https://www.google.com")
        // The POST data in the plain text format.
        .postData("Some Text...")
        // The Content-Type header that tells a web server
        // we sent POST data in the text/plain format.
        .addExtraHeader(HttpHeader.of("Content-Type", "text/plain"))
        .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("https://www.google.com")
        // The POST data in the JSON format.
        .postData("{\"title\":\"Hello\"}")
        // The Content-Type header that tells a web server
        // we sent POST data in the application/json format.
        .addExtraHeader(HttpHeader.of("Content-Type", "application/json"))
        .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("<html><body>Hello</body></html>")
        .baseUrl("<url>")
        .textEncoding("UTF-8")
        .mimeType(MimeType.of("text/html"))
        .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("<html><body>HTML Text</body></html>")
        .baseUrl("<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:

for (int index = 0; index < navigation.entryCount(); index++) {
    NavigationEntry navigationEntry = navigation.entryAtIndex(index);
    System.out.println("URL: " + navigationEntry.url());
    System.out.println("Title: " + navigationEntry.title());
}

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

// Returns the number of entries in the back/forward list.
int entryCount = navigation.entryCount();
// 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 navigation request to a specific URL should be ignored or not.

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

navigation.set(StartNavigationCallback.class, params -> {
    // Ignore navigation requests to the URLs that start 
    // with "https://www.google"
    if (params.url().startsWith("https://www.google")) {
        return Response.ignore();
    } 
    return Response.start();
});

Filtering Resources

Using the BeforeUrlRequestCallback 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 register your own callback implementation where you decide what resources should be canceled or loaded.

The following example demonstrates how to suppress all images:

Network network = engine.network();
network.set(BeforeUrlRequestCallback.class, params -> {
    if (params.urlRequest().resourceType() == IMAGE) {
        return BeforeUrlRequestCallback.Response.cancel();
    }
    return BeforeUrlRequestCallback.Response.proceed();
});

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:

navigation.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:

navigation.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:

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

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

navigation.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:

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

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

navigation.on(NavigationFinished.class, event -> {
    String url = event.url();
    Frame frame = event.frame();
    boolean hasCommitted = event.hasCommitted();
    boolean isSameDocument = event.isSameDocument();
    boolean isErrorPage = event.isErrorPage();
    if (isErrorPage) {
        NetError error = event.error();
    }
});

This event is fired when navigation is committed, aborted, or replaced by a new one. To know if the navigation has committed, use NavigationFinished.hasCommitted(); use NavigationFinished.isErrorPage() 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.isSameDocument() 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:

navigation.on(FrameLoadFinished.class, event -> {
    String url = event.url();
    Frame frame = event.frame();
});

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

Frame Load Failed

To get notifications when content loading in the Frame has failed for some reason, use the FrameLoadFailed event. For example:

navigation.on(FrameLoadFailed.class, event -> {
    String url = event.url();
    NetError error = event.error();
});

Frame Document Load Finished

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

navigation.on(FrameDocumentLoadFinished.class, event -> {
    Frame frame = event.frame();
});

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

Go Top