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 load a web page by its URL use the Browser.loadURL()
method. The following code demonstrates how to load http://www.google.com
web page:
browser.loadURL("http://www.google.com");
The web page will be loaded asynchronously, so there’s no guarantee that Google web page will be loaded completely when the method returns.
Loading URL with POST
To load web page by its URL and send some POST data, use the Browser.loadURL(LoadURLParams params)
method. The following code demonstrates how to load URL and send POST data in different formats using extra headers:
browser.loadURL(new LoadURLParams("http://www.google.com",
"myKey=myValue&myKey2=myValue2"));
browser.loadURL(new LoadURLParams("http://www.google.com",
"Some Text...", "Content-Type: text/plain\n"));
browser.loadURL(new LoadURLParams("http://www.google.com",
"{\"title\":\"Hello\"}", "Content-Type: application/json\n"));
Loading URL and Waiting
In some cases (e.g. automation testing) you might need to block current thread execution and wait until web page is loaded completely. JxBrowser API provides functionality that allows doing it. The following sample code demonstrates how to load http://www.google.com
web page and wait until it’s loaded completely:
Browser.invokeAndWaitFinishLoadingMainFrame(browser, new Callback<Browser>() {
@Override
public void invoke(Browser value) {
value.loadURL("http://www.google.com");
}
});
Use this method for loading web pages only.
Loading File
Same method can be used for loading a HTML file from a local file system. Instead of URL you just need to provide absolute path to HTML file. For example:
browser.loadURL("C:\\path\\index.html");
Loading HTML
To load HTML content from a string use the Browser.loadHTML()
method. For example:
browser.loadHTML("<html><body><h1>Load HTML Sample</h1></body></html>");
Loading HTML from JAR
JxBrowser allows loading HTML by URL, from local HTML file, from a String. Very often Java application resources such as HTML files are located inside JAR archives included into application class path. To be able to load resources located inside JAR archive you must register custom ProtocolHandler with the following implementation:
BrowserContext browserContext = browser.getContext();
ProtocolService protocolService = browserContext.getProtocolService();
protocolService.setProtocolHandler("jar", new ProtocolHandler() {
@Override
public URLResponse onRequest(URLRequest request) {
try {
URLResponse response = new URLResponse();
URL path = new URL(request.getURL());
InputStream inputStream = path.openStream();
DataInputStream stream = new DataInputStream(inputStream);
byte[] data = new byte[stream.available()];
stream.readFully(data);
response.setData(data);
String mimeType = getMimeType(path.toString());
response.getHeaders().setHeader("Content-Type", mimeType);
return response;
} catch (Exception ignored) {}
return null;
}
});
The getMimeType()
method returns appropriate mime type for the given resource extension:
private static String getMimeType(String path) {
if (path.endsWith(".html")) {
return "text/html";
}
if (path.endsWith(".css")) {
return "text/css";
}
if (path.endsWith(".js")) {
return "text/javascript";
}
return "text/html";
}
You can extend this method with additional extensions and mime types.
Once you register ProtocolHandler
and define what mime types are supported, you can load resources from JAR archive using standard Java and JxBrowser API. For example:
browser.loadURL(getClass().getResource("index.html").toString());
The complete example you can find below:
import com.teamdev.jxbrowser.chromium.*;
import com.teamdev.jxbrowser.chromium.swing.BrowserView;
import javax.swing.*;
import java.awt.*;
import java.io.DataInputStream;
import java.io.InputStream;
import java.net.URL;
public class ProtocolHandlerSample {
public static void main(String[] args) {
final Browser browser = new Browser();
BrowserView view = new BrowserView(browser);
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
frame.add(view, BorderLayout.CENTER);
frame.setSize(700, 500);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
BrowserContext browserContext = browser.getContext();
ProtocolService protocolService = browserContext.getProtocolService();
protocolService.setProtocolHandler("jar", new ProtocolHandler() {
@Override
public URLResponse onRequest(URLRequest request) {
try {
URLResponse response = new URLResponse();
URL path = new URL(request.getURL());
InputStream inputStream = path.openStream();
DataInputStream stream = new DataInputStream(inputStream);
byte[] data = new byte[stream.available()];
stream.readFully(data);
response.setData(data);
String mimeType = getMimeType(path.toString());
response.getHeaders().setHeader("Content-Type", mimeType);
return response;
} catch (Exception ignored) {}
return null;
}
});
// Assume that we need to load a resource related to this class in the JAR file
browser.loadURL(ProtocolHandlerSample.class.getResource("index.html").toString());
}
private static String getMimeType(String path) {
if (path.endsWith(".html")) {
return "text/html";
}
if (path.endsWith(".css")) {
return "text/css";
}
if (path.endsWith(".js")) {
return "text/javascript";
}
return "text/html";
}
}
Navigation History
JxBrowser provides API for working with navigation history. Using this API you can get information about navigation entries, got to entry at specified index, remove navigation entries, etc.
When you create a Browser
instance it navigates to the about:blank
web page by default, so there’s always one entry in navigation history.
Return the number of entries in the back/forward list.
int entryCount = browser.getNavigationEntryCount();
Return index of the current navigation entry in the back/forward list.
int index = browser.getCurrentNavigationEntryIndex();
Navigate to the entry at a specific index in the back/forward list.
browser.goToIndex(index);
Remove navigation entry from the back/forward list at a specific index.
boolean success = browser.removeNavigationEntryAtIndex(index);
Print information about the navigation entry at specific index.
NavigationEntry navigationEntry = browser.getNavigationEntryAtIndex(index);
System.out.println("URL = " + navigationEntry.getURL());
System.out.println("Original URL = " + navigationEntry.getOriginalURL());
System.out.println("Title = " + navigationEntry.getTitle());
Filtering URLs
JxBrowser API provides functionality that you can use to handle loading and decide whether specified URL should be loaded in Chromium engine or not. The following example demonstrates how to register LoadHandler
and cancel navigation to all URL that starts with http://www.google
:
browser.setLoadHandler(new DefaultLoadHandler() {
public boolean onLoad(LoadParams params) {
// Cancel loading URL that starts with http://www.google
return params.getURL().startsWith("http://www.google");
}
});
Filtering Resources
Using ResourceHandler
you can determine whether resources such as HTML, Images, JavaScript & CSS files, favicon, etc. should be loaded or not. By default all resources are loaded. To modify default behavior you need to register your own ResourceHandler
implementation. For example:
NetworkService networkService = browser.getContext().getNetworkService();
networkService.setResourceHandler(new ResourceHandler() {
@Override
public boolean canLoadResource(ResourceParams params) {
boolean isNotAnImageType =
params.getResourceType() != ResourceType.IMAGE;
if (isNotAnImageType) {
return true;
}
// Cancel loading of all images
return false;
}
});
Navigation Events
The LoadListener
provides methods for receiving browser load events. You can use this listener to get notifications about web page loading events, document availability events, loading failure events etc. The following code demonstrates how to register LoadListener
:
browser.addLoadListener(new LoadAdapter() {
@Override
public void onStartLoadingFrame(StartLoadingEvent event) {
if (event.isMainFrame()) {
System.out.println("Main frame has started loading");
}
}
@Override
public void onProvisionalLoadingFrame(ProvisionalLoadingEvent event) {
if (event.isMainFrame()) {
System.out.println("Provisional load was committed for a frame");
}
}
@Override
public void onFinishLoadingFrame(FinishLoadingEvent event) {
if (event.isMainFrame()) {
System.out.println("Main frame has finished loading");
}
}
@Override
public void onFailLoadingFrame(FailLoadingEvent event) {
NetError errorCode = event.getErrorCode();
if (event.isMainFrame()) {
System.out.println("Main frame has failed loading: " + errorCode);
}
}
@Override
public void onDocumentLoadedInFrame(FrameLoadEvent event) {
System.out.println("Frame document is loaded.");
}
@Override
public void onDocumentLoadedInMainFrame(LoadEvent event) {
System.out.println("Main frame document is loaded.");
}
});