JxBrowser Programmer’s Guide
Version: 3.4
- Introduction
- Requirements
- Browser Engines
- 3.1 Mozilla
- 3.2 Internet Explorer
- 3.3 Safari
- Libraries
- Navigating to URL
- Navigating to URL with POST data
- Browser Events
- Pop-up Windows
- Dialogs
- JavaScript
- JavaScript-Java Bridge
- Cookie Management
- User-Agent String
- DOM API
- DOM Events
- JxBrowser & Java Web Start
- JxBrowser & Java Applet
- System Properties
- Technical Support
1. Introduction
Any Java programmer, who has ever developed a Web site testing tool or desktop Java application with an HTML viewer, needs a library that could load, display an HTML document and access its content. Of course, the implementation of such library from scratch may take a lot of programming and testing efforts. Therefore, integrating an existing browser is preferable.
JxBrowser is a cross-platform library that enables seamless integration of Mozilla Firefox web browser into Java AWT/Swing applications on Windows, Linux, Mac OS X platforms, Microsoft Internet Explorer on Windows and Apple Safari on Mac OS X platform.
All JxBrowser engines support the same API, so you can easily switch between them.
2. Requirements
Different JxBrowser engines can support different platforms. Please see the list of supported platforms to make sure that a required JxBrowser engine supports your environment.
2.1. Windows
- Microsoft Windows XP/Vista/7, x86 or x64
- Oracle Java SE 1.5.x, 1.6.x, 1.7.0_09 32-bit or 64-bit.
2.2. Linux
- Linux Kernel 2.6
- Oracle Java SE 1.6.0_12-1.6.0_37 32-bit or 64-bit
- GTK 2.14+ with all dependent packages
- gtkmm 2 with all dependent packages (libsigc++ 2.x, GTK+ 2.x, cairomm)
- X Server must be started and running.
2.3. Mac OS X
- Mac OS X 10.7 (Intel) 32-bit or 64-bit, Apple Java 1.6.
- Mac OS X 10.8 (Intel) 32-bit or 64-bit, Apple Java 1.6.
- Mac OS X 10.7 (Intel) 64-bit, Oracle Java 1.7.0_09.
- Mac OS X 10.8 (Intel) 64-bit, Oracle Java 1.7.0_09.
3. Browser Engines
JxBrowser library allows using three browser engines in your Java Swing/AWT application: Mozilla Firefox, Internet Explorer and Safari.
To create a default browser engine for the current platform, you can use the following code:
Browser browser = BrowserFactory.createBrowser();
This method creates a different engine on different platforms:
- on Windows it returns Internet Explorer engine
- on Linux platforms the method returns Mozilla engine
- on Mac OS X it creates a Safari engine.
To find out which browser engine will be created on the current operating system use the following code:
BrowserType browserType = BrowserFactory.getDefaultBrowserType();
if (browserType == BrowserType.IE) {
// IE engine is default for the current operating system
}
if (browserType == BrowserType.Mozilla) {
// Mozilla engine is default for the current operating system
}
if (browserType == BrowserType.Safari) {
// Safari engine is default for the current operating system
}
Please refer to the following chapters to find out how to create a specific browser engine.
3.1. Mozilla
To create Mozilla Firefox browser engine that based on XULRunner 1.9.2 use the following code:
Browser browser = BrowserFactory.createBrowser(BrowserType.Mozilla);
This engine supports Windows, Linux and Mac OS X platforms.
To find out whether this engine supports the current operating system use the following code:
if (BrowserType.Mozilla.isSupported()) {
// Mozilla is supported on the current operating system
}
To create Mozilla Firefox browser engine that based on XULRunner 15 use the following code:
Browser browser = BrowserFactory.createBrowser(BrowserType.Mozilla15);
This engine supports Windows and Mac OS X platforms.
To find out whether this engine supports the current operating system use the following code:
if (BrowserType.Mozilla15.isSupported()) {
// Mozilla is supported on the current operating system
}
These engines don't require Mozilla Firefox to be installed in operating system. All required libraries for this engine are located in JxBrowser distribution package.
Please note that Mozilla and Mozilla15 cannot be used at the same time.
3.2. Internet Explorer
To create IE browser engine use the following code:
Browser browser = BrowserFactory.createBrowser(BrowserType.IE);
This engine supports only Windows platform. It requires that MS Internet Explorer 6.0-9.0 is installed in operating system.
3.3. Safari
To create Safari engine use the following code:
Browser browser = BrowserFactory.createBrowser(BrowserType.Safari);
This engine supports only Mac OS X (Intel) 10.7 and 10.8 platforms. It requires that Apple Safari is installed in operating system.
4. Libraries
JxBrowser distribution package includes libraries for all browser engines and supported platforms (Windows, Mac OS X and Linux). Below you can find the list of required libraries for each engine/platform.
Core libraries for all engines/platforms:
- jxbrowser-x.x.jar
- jniwrap-x.x.jar
- slf4j-api-x.x.jar
- slf4j-log4j12-x.x.jar
- log4j-x.x.jar
Mozilla/Windows (only JDK 32-bit):
- engine-gecko.jar
- xulrunner-windows.jar
- winpack-x.x.jar
Mozilla/Linux (JDK 32-bit or 64-bit):
- engine-gecko.jar
- xulrunner-linux.jar
- xulrunner-linux64.jar
Mozilla/Mac OS X (JDK 32-bit, JDK 64-bit with enabled 32-bit mode only):
- engine-gecko.jar
- xulrunner-mac.jar
Mozilla15/Windows (only JDK 32-bit):
- engine-gecko15.jar
- xulrunner15-windows.jar
- winpack-x.x.jar
Mozilla15/Mac OS X (JDK 32-bit or JDK 64-bit):
- engine-gecko15.jar
- xulrunner15-mac.jar
IE/Windows (JDK 32- or 64-bit):
- engine-ie.jar
- comfyj-x.x.jar
- winpack-x.x.jar
Safari/Mac OS X (JDK 32- or 64-bit):
- engine-webkit.jar
Using all JxBrowser libraries increases the size of Java application. The size of all JxBrowser libraries is ~100MB. To decrease the size of your Java application please use only required libraries.
5. Navigating to URL
To open a web page or a local HTML document use the following code:
Browser browser = BrowserFactory.createBrowser();
browser.navigate("http://www.google.com");
The Browser.navigate() method navigates to a document identified by a URL or to a file identified by a full path. It doesn't block the current thread execution until the document is loaded completely. To make sure that the document is loaded completely use one of the following ways:
-
Use the
NavigationListener.navigationFinished()event. This event is invoked when navigation is finished and a document has been completely loaded and initialized. In pages with no frames or where multiple frames are loaded, this event fires once after loading is completed. Example:browser.addNavigationListener(new NavigationAdapter() { @Override public void navigationFinished(NavigationFinishedEvent event) { // document is loaded completely } }); browser.navigate("http://www.google.com"); -
Use the
Browser.waitReady()method. This method blocks the current thread execution until the document is loaded completely. Example:browser.navigate("http://www.google.com"); browser.waitReady();Do not invoke this method in Java Swing UI thread because it will block it until the document is loaded completely.
Some web pages cause an issue when browser engine doesn't receive notification that web page is loaded completely. So, if web page was not loaded within 45 seconds the
Browser.waitReady()method stop waiting.
6. Navigating to URL with POST data
To navigate to a web page with HTTP POST data use the following code:
browser.navigate("http://www.google.com", "name=Alex&product=Pizza");
7. Browser Events
Browser engines send notifications about their various events related to navigation, document loading completion, document title, status text change, etc.
To listen navigation started and navigation finished events use the following code:
browser.addNavigationListener(new NavigationListener() {
public void navigationStarted(NavigationEvent event) {
System.out.println("event.getUrl() = " + event.getUrl());
}
public void navigationFinished(NavigationFinishedEvent event) {
System.out.println("event.getStatusCode() = " + event.getStatusCode());
}
});
To listen for document title change events use the TitleListener:
browser.addTitleListener(new TitleListener() {
public void titleChanged(TitleChangedEvent event) {
System.out.println("event.getTitle() = " + event.getTitle());
}
});
To receive status text changed events use the StatusListener:
browser.addStatusListener(new StatusListener() {
public void statusChanged(StatusChangedEvent event) {
System.out.println("event.getStatusText() = " + event.getStatusText());
}
});
Any browser instance can be disposed from JavaScript. To receive notification that browser was disposed please use the DisposeListener:
browser.addDisposeListener(new DisposeListener() {
public void browserDisposed(DisposeEvent event) {
}
});
8. Pop-up Windows
By default JxBrowser displays all pop-up windows. To change the default behavior you can implement and register your own com.teamdev.jxbrowser.NewWindowManager. The following code demonstrates how to do this:
Browser browser = BrowserFactory.createBrowser();
browser.getServices().setNewWindowManager(new NewWindowManager() {
public NewWindowContainer evaluateWindow(final NewWindowParams params){
return new NewWindowContainer() {
public void insertBrowser(final Browser browser) {
final JFrame popupFrame = new JFrame();
Container contentPane = popupFrame.getContentPane();
contentPane.add(browser.getComponent(), BorderLayout.CENTER);
// sets window bounds using popup window params
popupFrame.setBounds(params.getBounds());
popupFrame.setVisible(true);
// registers window listener to dispose Browser instance on window close
popupFrame.addWindowListener(new WindowAdapter() {
@Override
public void windowClosing(WindowEvent e) {
browser.dispose();
}
});
// registers Browser dispose listener to dispose window when Browser
// is disposed (e.g. using the window.close JavaScript function)
browser.addDisposeListener(new DisposeListener() {
public void browserDisposed(DisposeEvent event) {
popupFrame.dispose();
}
});
}
};
}
});
To suppress all pop-up windows you can use the following code:
browser.getServices().setNewWindowManager(new NewWindowManager() {
public NewWindowContainer evaluateWindow(NewWindowParams params) {
return null;
}
});
9. Dialogs
By default JxBrowser displays all dialogs such as JavaScript alert, confirmation, prompt or JavaScript error. To handle dialogs register your own implementation of the com.teamdev.jxbrowser.prompt.PromptService using the BrowserServices.setPromptService() method.
To suppress all dialogs use the com.teamdev.jxbrowser.prompt.SilentPromptService implementation:
BrowserServices.getInstance().setPromptService(new SilentPromptService());
You can also override default implementation of PromptService and provide your own behavior for a specified dialog. For example, to suppress only confirmation dialogs and always return CANCEL value you can use the following code:
browser.getServices().setPromptService(new DefaultPromptService() {
@Override
public void alertRequested(DialogParams params) {
super.alertRequested(params);
}
@Override
public CloseStatus promptRequested(PromptDialogParams params) {
return super.promptRequested(params);
}
@Override
public CloseStatus confirmationRequested(DialogParams params) {
return CloseStatus.CANCEL;
}
@Override
public CloseStatus loginRequested(LoginParams params) {
return super.loginRequested(params);
}
@Override
public CloseStatus scriptErrorRequested(ScriptErrorParams params) {
return super.scriptErrorRequested(params);
}
});
10. JavaScript
Using the Browser.executeScript() method you can execute any JavaScript code on the loaded web page:
browser.executeScript("document.write('Hello from JxBrowser!');");
This method returns the result of JavaScript execution as a String value. Before you invoke this method please make sure that the document is loaded completely. You can use the Browser.waitReady() method for this:
browser.navigate("http://www.google.com");
browser.waitReady();
String title = browser.executeScript("document.title");
System.out.println("title = " + title);
11. JavaScript-Java Bridge
In JxBrowser 3.0 was introduced JavaScript-Java bridge functionality that allows invoking Java methods from JavaScript side. The following sample demonstrates how to register the MyFunction JavaScript function on the current web page:
browser.registerFunction("MyFunction", new BrowserFunction() {
public Object invoke(Object... args) {
for (Object arg : args) {
System.out.println("arg = " + arg);
}
return "MyFunction Result";
}
});
browser.executeScript("alert(MyFunction('Arg1', 'Arg2', 100, 200.1));");
The MyFunction method is available only for the currently loaded web page. If you reload web page or navigate to another URL, this method will not be available anymore.
12. Cookie Management
Each browser engine has its own Cookie Storage. To access Mozilla Cookie Storage use the following code:
Browser browser = BrowserFactory.createBrowser(BrowserType.Mozilla); HttpCookieStorage cookieStorage = browser.getCookieStorage(); // gets a list of available cookies List<HttpCookie> cookies = cookieStorage.getCookies();
You must create a browser instance before accessing its Cookie Storage.
13. User-Agent String
The User-Agent string can be changed programatically using the Browser.setUserAgent() method. For example:
Browser browser = BrowserFactory.createBrowser(BrowserType.Mozilla);
browser.setUserAgent("My User-Agent String");
To restore a default User-Agent string use the following way:
browser.setUserAgent(null);
14. DOM API
JxBrowser provides API that allows accessing the loaded web page DOM. JxBrowser DOM API is based on standard Java W3C DOM API from the org.w3c.dom package. Before accessing the web page DOM, make sure that web page is loaded completely using the Browser.waitReady() method.
browser.navigate("http://www.google.com");
browser.waitReady();
HTMLDocument document = (HTMLDocument) browser.getDocument();
// Set value into search field
HTMLElement searchField = (HTMLElement) document.getElementsByName("q").item(0);
searchField.setAttribute("value", "TeamDev");
15. DOM Events
JxBrowser DOM API supports DOM Event Listeners. You can register DOM EventListener for any Element on the loaded web page:
Document document = browser.getDocument();
Element documentElement = document.getDocumentElement();
((EventTarget) documentElement).addEventListener("click", new EventListener() {
public void handleEvent(Event evt) {
System.out.println("Type = " + evt.getType());
}
}, false);
Before accessing the web page DOM, make sure that web page is loaded completely using the Browser.waitReady() method.
16. JxBrowser & Java Web Start
This section describes how you can deploy your application that uses JxBrowser with Java Web Start technology. Below you can find how JxBrowserDemo JNLP (JxBrowserDemo.jnlp) file looks like:
<jnlp spec="1.5+" codebase="http://www.teamdev.com" href="JxBrowserDemo.jnlp">
<information>
<title>JxBrowserDemo</title>
<vendor>TeamDev Ltd.</vendor>
<homepage href="http://www.teamdev.com/jxbrowser"/>
<description>JxBrowser Demo Application</description>
<offline-allowed/>
</information>
<security>
<all-permissions/>
</security>
<application-desc main-class="com.teamdev.jxbrowser.demo.JxBrowserDemo"/>
<resources>
<jar href="lib/jxbrowserdemo.jar" main="true"/>
<jar href="lib/jxbrowser-x.x.jar"/>
<jar href="lib/jniwrap-x.x.jar"/>
<jar href="lib/engine-gecko.jar"/>
<jar href="lib/log4j-x.x.jar"/>
<jar href="lib/slf4j-api-x.x.jar"/>
<jar href="lib/slf4j-log4j12-x.x.jar"/>
</resources>
<resources os="Windows">
<j2se version="1.5+" initial-heap-size="128m" max-heap-size="512m"/>
<jar href="lib/engine-ie.jar"/>
<jar href="lib/comfyj-x.x.jar"/>
<jar href="lib/winpack-x.x.jar"/>
<jar href="lib/xulrunner-windows.jar"/>
</resources>
<resources os="Mac OS X">
<j2se version="1.5+" initial-heap-size="128m" max-heap-size="512m" java-vm-args="-d32"/>
<jar href="lib/engine-webkit.jar"/>
<jar href="lib/xulrunner-mac.jar"/>
</resources>
<resources os="Linux">
<j2se version="1.6+" initial-heap-size="128m" max-heap-size="512m"/>
</resources>
<resources os="Linux" arch="ppc i386 i686">
<jar href="lib/xulrunner-linux.jar"/>
</resources>
<resources os="Linux" arch="x86_64 amd64">
<jar href="lib/xulrunner-linux64.jar"/>
</resources>
</jnlp>
Please note that JNLP file must contains the following options to successfully start JxBrowser library:
<security>
<all-permissions/>
</security>
JxBrowser Online Demo JNLP file is configured to use the following libraries:
jxbrowserdemo.jar— the JxBrowser Demo application library with the main classlog4j-x.x.jar, slf4j-api-x.x.jar, slf4j-log4j12-x.x.jar— logging librariesjxbrowser-x.x.jar— JxBrowser API libraryjniwrap-x.x.jar— JNIWrapper library provides simplified access to native code from Java applications without using Java Native Interface (JNI)comfyj-x.x.jar— ComfyJ library — is a Java-COM bridge enabling bidirectional communication between the Java platform and COM technologiesengine-ie.jar— Microsoft IE engineengine-gecko.jar— Mozilla engineengine-webkit.jar— Apple Safari enginewinpack-x.x.jar— Windows native APIxulrunner-windows.jar, xulrunner-linux.jar, xulrunner-linux64.jar, xulrunner-mac.jar— Mozilla XULRunner packages for Windows, Linux and Mac OS X
To deploy your application via Java Web Start, please follow the steps below:
Pack your application classes into application JAR file(s) (
demo.jar);Put JxBrowser Runtime license file (teamdev.licenses) into META-INF folder of your application JAR file. For this you can use the following ANT script:
<jar destfile="${demoJarName}"> <fileset dir="${classes}" includes="**/**" /> <zipfileset dir="${srcPath}/lic" includes="teamdev.licenses" prefix="META-INF" /> ... </jar>where:
${classes} — path to class files of demo application;
${srcPath}/lic — path to theteamdev.licenseslicence file;Or you can use the jar tool to update your application JAR file (
demo.jar). Create META-INF folder and copyteamdev.licensesfile into it. Run the following command in command line:jar uf demo.jar META-INF\teamdev.licenses
Sign all your application JAR files. Please note that by default all JxBrowser libraries are signed with TeamDev signature. For this purpose, you can use the following ANT templates:
Create and configure your application JNLP file;
Upload your application JAR files, JxBrowser JAR files and JNLP file to a web-server.
<project name="Sample" default="build" basedir=".">
<target name="demojar">
<property name="demoJarName" value="demo.jar"/>
<signjar jar="${demoJarName}" alias="your_alias" keystore="your_keystore"
keypass="your_keypass" storepass="your_storepass"/>
</target>
</project>
where:your_alias, your_keystore, your_keypass, your_storepass — signjar parameters. You can see their description in Apache Ant User Manual.
Or you can use the jarsigner tool to sign your application JAR file:
jarsigner -keystore keystore_file -storepass storepass -keypass keypass demo.jar alias
Please note that JxBrowser libraries are already signed with TeamDev signature. In order to use already signed JxBrowser libraries with your application JNLP file you can use the <extension> tag. This technique is demonstrated in the example below. The first file is application JNLP file (demo.jnlp):
<jnlp spec="1.5+" codebase="http://codebase" href="demo.jnlp">
<information>
<title>Demo Application</title>
<vendor>TeamDev Ltd.</vendor>
<description>Demo Application</description>
<offline-allowed/>
</information>
<security>
<all-permissions/>
</security>
<resources>
<j2se version="1.5+" initial-heap-size="64m" max-heap-size="256m"/>
<!-- demo.jar is your jar file signed with your own signature-->
<jar href="demo.jar"/>
<extension name="jxbrowser" href="JxBrowser.jnlp"/>
</resources>
<application-desc main-class="main_class"/>
</jnlp>
The <extension> tag above makes the reference to jxbrowser.jnlp:
<jnlp spec="1.5+" codebase="http://codebase" href="JxBrowser.jnlp">
<information>
<title>JxBrowser resources</title>
<vendor>TeamDev Ltd.</vendor>
<homepage href="http://www.teamdev.com/jxbrowser"/>
<offline-allowed/>
</information>
<security>
<all-permissions/>
</security>
<component-desc/>
<resources>
<jar href="lib2/jxbrowser-x.x.jar" />
<jar href="lib2/jniwrap-x.x.jar" />
<jar href="lib2/engine-gecko.jar" />
<jar href="lib2/log4j-x.x.jar" />
<jar href="lib2/slf4j-api-x.x.jar" />
<jar href="lib2/slf4j-log4j12-x.x.jar" />
</resources>
<resources os="Windows">
<j2se version="1.5+" initial-heap-size="128m" max-heap-size="512m"/>
<jar href="lib2/engine-ie.jar" />
<jar href="lib2/comfyj-x.x.jar" />
<jar href="lib2/winpack-x.x.jar" />
<jar href="lib2/xulrunner-windows.jar" />
</resources>
<resources os="Mac OS X">
<j2se version="1.5+" initial-heap-size="128m" max-heap-size="512m" java-vm-args="-d32"/>
<jar href="lib2/engine-webkit.jar" />
<jar href="lib2/xulrunner-mac.jar" />
</resources>
<resources os="Linux">
<j2se version="1.6+" initial-heap-size="128m" max-heap-size="512m"/>
</resources>
<resources os="Linux" arch="ppc i386 i686">
<jar href="lib/xulrunner-linux.jar" />
</resources>
<resources os="Linux" arch="x86_64 amd64">
<jar href="lib/xulrunner-linux64.jar" />
</resources>
</jnlp>
17. JxBrowser & Java Applet
You can use JxBrowser in Java Applet in the same way as standard Java library.
JxBrowser requires access to the file system, so you should sign all libraries in your Java Applet application including all JxBrowser libraries.
By default all JxBrowser libraries are signed with TeamDev signature. So, you need to remove TeamDev signature before signing them using your signature. To remove TeamDev signatures you must remove the META-INF\TEAMDEVC.RSA and META-INF\TEAMDEVC.SF files from each JAR in JxBrowser distribution package.
When all your application JARs are signed, including all required JxBrowser libraries, you can configure your APPLET tag:
<APPLET code="Application.class" codebase="." archive="application.jar,<List of required
JxBrowser JARs>" WIDTH=800 HEIGHT=400>Browser doesn't support Java Applets.</APPLET>
18. System Properties
JxBrowser library uses several System Properties which can be useful for you. You should set up these properties before creating a browser instance.
To print license information in console use:
System.setProperty("teamdev.license.info", "true");
By default out-process implementation of IE engine is used on JDK 32-bit. In this case each browser instance is running in a separate native process JExplorer32.x.x.exe. To disable this functionality and run each browser instance in Java process use:
System.setProperty("JExplorer.runInIsolatedProcess", "false");
By default Mozilla XULRunner is extracted into the USER_HOME\.JxBrowser directory. To provide custom path to the directory where XULRunner should be extracted use the following property:
System.setProperty("jxbrowser.xulrunner.dir", "path-to-directory");
By default Mozilla profile directory will be created in the USER_HOME\.JxBrowser directory. To provide custom path to the profile directory use:
System.setProperty("jxbrowser.xulrunner.profile.dir", "path-to-directory");
To disable Mozilla profile at all use the following system property:
System.setProperty("jxbrowser.xulrunner.use.profile", "false");
By default Mozilla XULRunner is extracted into the USER_HOME\.JxBrowser directory. XULRunner extraction may take several seconds. To avoid extraction you can provide a path to the directory with already extracted XULRunner:
System.setProperty("GRE_HOME", "path-to-directory");
To enable Mozilla Firefox plugins in JxBrowser Mozille engine you can provide the path to the directory where Mozilla plugins are located. You can provide multiple plugin directories separated by ";":
System.setProperty("jxbrowser.plugin.dir", "path-to-plugin-directory;path-to-plugin-directory");
19. Technical Support
JxBrowser Support Site
You can find more information about how to use JxBrowser library at JxBrowser Support Site.
JxBrowser Samples
You can find JxBrowser samples on the following resource: https://sites.google.com/a/teamdev.com/jxbrowser-support/samples
Reporting Problems
If you have any questions regarding JxBrowser, please e-mail us at: jxbrowser-evaluation@teamdev.com
JxBrowser Forum
If you would like to discuss any topics related to JxBrowser, please visit our Support Forum.