New version is available You are viewing the documentation for JxBrowser 6 which is not supported since December 2019. Go to the current documentation.
List icon 目录

This guide describes how to access a DOM document, find elements, modify a DOM structure, simulate user input, etc.

Accessing Document

Each web page loaded in the browser has its own document object. To access document object of loaded web page use the Browser.getDocument() method. This method returns DOMDocument instance that you can use to access document’s properties and its child nodes. For example:

DOMDocument document = browser.getDocument();

If web page contains frames (see IFRAME or FRAME), then each frame has its own document object. To access document object of a specified frame use the Browser.getDocument(long frameId) method. The frameId you can obtain from the Browser.getFramesIds() method. For example:

for (Long frameId : browser.getFramesIds()) {
    DOMDocument frameDocument = browser.getDocument(frameId);
}

Having DOMDocument instance you can work with the document object and its DOM structure.

If web page isn’t completely loaded or it doesn’t have document, then the Browser.getDocument() method returns null. So, before you invoke this method, make sure that web page is loaded completely.

Finding Elements

JxBrowser DOM API provides functionality that can be used for finding HTML elements on loaded web page by different conditions. The following sample code demonstrates how to find all HTML elements by specified tag name:

List<DOMElement> divs = document.findElements(By.tagName("div"));

If you need to find only first HTML element in the document use the following approach:

DOMElement div = document.findElement(By.id("myId"));

In general you can search for HTML elements using different conditions:

DOMElement element = document.findElement(By.id("myId"));
DOMElement element = document.findElement(By.tagName("div"));
DOMElement element = document.findElement(By.className("myClass"));
DOMElement element = document.findElement(By.name("myName"));
DOMElement element = document.findElement(By.xpath("//textarea"));
DOMElement element = document.findElement(By.cssSelector("#root"));

Element Attributes

To access the attributes of an HTML element use the following approach:

DOMElement link = document.findElement(By.id("link"));
Map<String, String> attributes = link.getAttributes();
for (String attrName : attributes.keySet()) {
    System.out.println(attrName + " = " + attributes.get(attrName));
}

Creating Element & Text Node

The following sample demonstrates how to create DOM elements:

DOMNode root = document.findElement(By.id("root"));
DOMNode textNode = document.createTextNode("Some text");
DOMElement paragraph = document.createElement("p");
paragraph.appendChild(textNode);
root.appendChild(paragraph);

Setting Node Value

DOMElement button = document.findElement(By.id("button-id"));
button.getChildren().get(0).setNodeValue("New Button Name");

Select and Option Elements

JxBrowser DOM API allows working with the HTML SELECT and OPTION elements. To work with the SELECT element, the DOMSelectElement class is used. Let’s see how to access SELECT element on web page that contains the following HTML code:

<select id='select-tag'>
  <option value="volvo">Volvo</option>
  <option value="saab">Saab</option>
  <option value="mercedes">Mercedes</option>
  <option value="audi">Audi</option>
</select>

To access the SELECT element use the following JxBrowser API:

DOMDocument document = browser.getDocument();
DOMSelectElement select = (DOMSelectElement) document.findElement(By.id("select-tag"));

Now, using the select instance you can get information about its options, programmatically select specified option. For example:

List<DOMOptionElement> options = select.getOptions();
options.get(2).setSelected(true);

Selecting CheckBox

To programmatically select/unselect HTML input type=checkbox element use the DOMInputElement.setChecked(boolean checked) method. The following sample demonstrates how to find checkbox element on loaded web page and select it:

DOMInputElement element = (DOMInputElement) document.findElement(By.name("agreement"));
element.setChecked(true);

Getting Selected Text

To get the currently selected text on a web page use the following API:

String selectedText = browser.getSelectedText();

Simulating Click

JxBrowser DOM API provides functionality that allows you to simulate click on any HTML element on the loaded web page. To simulate click you need to make sure that web page is loaded completely and find the required HTML element in document:

DOMDocument document = browser.getDocument();
DOMElement link = document.findElement(By.tagName("button"));

Once you get the reference to the required HTML element, you can simulate click using the DOMNode.click() method.

link.click();

Please note that this method works asynchronously. When this method returns, it doesn’t mean that click simulation is finished.

This functionality can be useful in automated testing when you need to simulate user actions including mouse clicks on specified HTML elements.

XPath

JxBrowser DOM API provides functionality that allows evaluating XPath expressions. You can evaluation XPath expression in scope of DOMDocument or specified DOMNode. Both DOMDocument and DOMNode implements the SearchContext interface that provides the following methods:

  • XPathResult evaluate(String expression)
  • XPathResult evaluate(String expression, XPathResultType type)
DOMDocument document = browser.getDocument();
XPathResult result = document.evaluate("count(//div)");

The result of evaluation is stored in the XPathResult object. First you need to make sure that result is not an error and the evaluation completed successfully:

if (result.isError()) {
    System.out.println("Error: " + result.getErrorMessage());
    return;
}

Then you need to make sure that result contains expected value type (e.g. Number, Boolean, String, DOMNode) and extract the value itself:

if (result.isNumber()) {
    System.out.println("Result: " + result.getNumber());
}

or

if (result.isString()) {
    System.out.println("Result: " + result.getString());
}

or

if (result.isSingleNode()) {
    DOMNode node = result.getSingleNode();
    System.out.println("Result: " + node.getTextContent());
}

Query Selector

// Get the div with id = "root".
DOMNode divRoot = document.findElement(By.cssSelector("#root"));
// Get all paragraphs.
List<DOMElement> paragraphs = divRoot.findElements(By.cssSelector("p"));
for (DOMElement paragraph : paragraphs) {
    System.out.println("paragraph.getNodeValue() = " +
            paragraph.getChildren().get(0).getNodeValue());
}

Scrolling Document

The following approach demonstrates how you can stroll displayed web page (document) at specified position using JavaScript:

browser.executeJavaScript(
            "window.scrollTo(document.body.scrollWidth, " +
            "document.body.scrollHeight);")

Node at Point

To find a DOMNode at specific location on a web page use the following approach:

DOMNodeAtPoint nodeAtPoint = browser.getNodeAtPoint(100, 200);

Getting Element Bounds

Sometimes it might be useful to get information about location and size of a specific HTML Element on the loaded web page relative to the top-left of the viewport of the current document (e.g. to highlight or capture it). The DOMElement.getBoundingClientRect() method returns the size of an element and its position relative to the viewport. It’s equivalent of the Web API Element.getBoundingClientRect() JavaScript function.

Injecting CSS

Since 6.14 version JxBrowser provides API that allows injecting custom style sheet (CSS) into every web page loaded in the Browser instance. The following example demonstrates how to use this functionality:

browser.setCustomStyleSheet("body { background-color: orange; }");

The injected CSS won’t override already defined CSS properties on the loaded web page.

To reset injected CSS call the browser.setCustomStyleSheet("") method.

Events

Each DOMNode implements DOMEventTarget interface that provides methods for registering DOM events. You can register DOM listener to receive DOM events such as click, mousedown, mouseup, keydown, load, error etc. The following sample demonstrates how to register click event listener for a document HTML element:

DOMElement element = document.getDocumentElement();
element.addEventListener(DOMEventType.OnClick, new DOMEventListener() {
    public void handleEvent(DOMEvent event) {
        // user clicked document element
    }
}, false);

You can register DOM event listener only for the document of the loaded web page. After reloading the web page, all the registered DOM event listeners will not work anymore, so you need to register the required DOM event listeners again.

Custom DOM Event Types

JxBrowser allows you to listen to the custom DOM Event types as well. The following code demonstrates how to listen to the MyEvent DOM Events:

DOMElement element = document.getDocumentElement();
element.addEventListener(new DOMEventType("MyEvent"), new DOMEventListener() {
    public void handleEvent(DOMEvent event) {
    }
}, false);

Dispatching DOM Events

Starting from JxBrowser version 6.13, JxBrowser DOM Events API got extended with new methods and classes, which allow creating and triggering DOM events at the specified HTML element. JxBrowser supports the Event, UIEvent, MouseEvent, and KeyEvent DOM events. To dispatch an event use the DOMEventTarget.dispatchEvent(DOMEvent event) method.

DOMEventType eventType = new DOMEventType("MyEvent");
DOMEvent myEvent = document.createEvent(eventType, new DOMEventParams());
DOMNode root = document.findElement(By.id("root"));

root.addEventListener(eventType, new DOMEventListener() {
    @Override
    public void handleEvent(DOMEvent event) {
        if (event.getType().equals(eventType)) {
            System.out.println("MyEvent received successfully");
        }
    }
}, false);

root.dispatchEvent(myEvent);
Go Top