Samples

In JxBrowser 4 we significantly improved previous version of public API taking into account multiple feedbacks from our customers. To help you migrate your code from 3.x API to 4.x API we prepared the migration document. 

Load URL

import com.teamdev.jxbrowser.chromium.Browser;
import com.teamdev.jxbrowser.chromium.BrowserFactory;

import javax.swing.*;
import java.awt.*;

/**
 * This sample demonstrates how to create JxBrowser instance,
 * add JxBrowser component to JFrame container and
 * navigate to the "www.google.com" web site.
 */
public class BrowserSample {
    public static void main(String[] args) {
        Browser browser = BrowserFactory.create();

        JFrame frame = new JFrame();
        frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        frame.add(browser.getView().getComponent(), BorderLayout.CENTER);
        frame.setSize(700, 500);
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);

        browser.loadURL("http://www.google.com");
    }
}

Load HTML

import com.teamdev.jxbrowser.chromium.Browser;
import com.teamdev.jxbrowser.chromium.BrowserFactory;
import com.teamdev.jxbrowser.chromium.events.FinishLoadingEvent;
import com.teamdev.jxbrowser.chromium.events.LoadAdapter;

import javax.swing.*;
import java.awt.*;

/**
 * This sample demonstrates how to load custom HTML string into
 * Browser component and display it.
 */
public class LoadHTMLSample {
    public static void main(String[] args) {
        Browser browser = BrowserFactory.create();

        JFrame frame = new JFrame();
        frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        frame.add(browser.getView().getComponent(), BorderLayout.CENTER);
        frame.setSize(700, 500);
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);

        browser.addLoadListener(new LoadAdapter() {
            @Override
            public void onFinishLoadingFrame(FinishLoadingEvent event) {
                if (event.isMainFrame()) {
                    System.out.println("HTML is loaded.");
                }
            }
        });
        browser.loadHTML("<html><body><h1>Load HTML Sample</h1></body></html>");
    }
}

Load Events

import com.teamdev.jxbrowser.chromium.Browser;
import com.teamdev.jxbrowser.chromium.BrowserFactory;
import com.teamdev.jxbrowser.chromium.events.*;

import javax.swing.*;
import java.awt.*;

/**
 * The sample demonstrates how to listen to different load events such as
 * 'start loading frame', 'finish loading frame', 'fail loading frame',
 * 'document loaded in frame' and 'document loaded in main frame'.
 */
public class LoadListenerSample {
    public static void main(String[] args) {
        Browser browser = BrowserFactory.create();

        JFrame frame = new JFrame();
        frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        frame.add(browser.getView().getComponent(), BorderLayout.CENTER);
        frame.setSize(800, 600);
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);

        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) {
                int 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.");
            }
        });

        browser.loadURL("http://www.google.com");
    }
}

Load Handler

import com.teamdev.jxbrowser.chromium.*;

import javax.swing.*;
import java.awt.*;

/**
 * This sample demonstrates how to cancel loading of a specific URL.
 */
public class LoadHandlerSample {
    public static void main(String[] args) {
        Browser browser = BrowserFactory.create();

        JFrame frame = new JFrame();
        frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        frame.add(browser.getView().getComponent(), BorderLayout.CENTER);
        frame.setSize(700, 500);
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);

        browser.setLoadHandler(new DefaultLoadHandler() {
            public boolean onLoad(LoadParams params) {
                String url = params.getURL();
                boolean cancel = url.startsWith("http://www.google");
                return cancel;
            }
        });
        browser.loadURL("http://www.google.com");
    }
}

SSL Certificate Error

import com.teamdev.jxbrowser.chromium.*;
import com.teamdev.jxbrowser.chromium.events.NetError;

import javax.swing.*;
import java.awt.*;

/**
 * Demonstrates how to handle SSL certificate errors.
 */
public class CertificateErrorSample {
    public static void main(String[] args) {
        Browser browser = BrowserFactory.create();

        JFrame frame = new JFrame();
        frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        frame.add(browser.getView().getComponent(), BorderLayout.CENTER);
        frame.setSize(700, 500);
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);

        browser.setLoadHandler(new DefaultLoadHandler() {
            @Override
            public boolean onCertificateError(CertificateErrorParams params) {
                Certificate certificate = params.getCertificate();
                System.out.println("certificate.getSubjectName() = " + certificate.getSubjectName());
                System.out.println("certificate.getIssuerName() = " + certificate.getIssuerName());
                System.out.println("certificate.hasExpired() = " + certificate.hasExpired());
                NetError errorCode = params.getCertificateError();
                System.out.println("errorCode = " + errorCode);
                // Return false to ignore certificate error.
                return false;
            }
        });
        browser.loadURL("<https-url-with-invalid-ssl-certificate>");
    }
}

Title Events

import com.teamdev.jxbrowser.chromium.Browser;
import com.teamdev.jxbrowser.chromium.BrowserFactory;
import com.teamdev.jxbrowser.chromium.events.TitleEvent;
import com.teamdev.jxbrowser.chromium.events.TitleListener;

import javax.swing.*;
import java.awt.*;

/**
 * The sample demonstrates how to listen to title change events.
 */
public class TitleListenerSample {
    public static void main(String[] args) {
        Browser browser = BrowserFactory.create();

        JFrame frame = new JFrame();
        frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        frame.add(browser.getView().getComponent(), BorderLayout.CENTER);
        frame.setSize(800, 600);
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);

        browser.addTitleListener(new TitleListener() {
            public void onTitleChange(TitleEvent event) {
                System.out.println("Title = " + event.getTitle());
            }
        });

        browser.loadURL("http://www.google.com");
    }
}

Popups

import com.teamdev.jxbrowser.chromium.*;
import com.teamdev.jxbrowser.chromium.events.DisposeEvent;
import com.teamdev.jxbrowser.chromium.events.DisposeListener;

import javax.swing.*;
import java.awt.*;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;

/**
 * The sample demonstrates how to register popup handler and
 * implement functionality that displays popup windows.
 */
public class PopupSample {
    public static void main(String[] args) {
        Browser browser = BrowserFactory.create();

        JFrame frame = new JFrame();
        frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        frame.add(browser.getView().getComponent(), BorderLayout.CENTER);
        frame.setSize(800, 600);
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);

        browser.setPopupHandler(new PopupHandler() {
            public PopupContainer handlePopup(PopupParams params) {
                return new PopupContainer() {
                    public void insertBrowser(final Browser browser, Rectangle initialBounds) {
                        JComponent component = browser.getView().getComponent();
                        component.setPreferredSize(initialBounds.getSize());

                        final JFrame frame = new JFrame("Popup");
                        frame.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
                        frame.add(component, BorderLayout.CENTER);
                        frame.pack();
                        frame.setLocation(initialBounds.getLocation());
                        frame.setVisible(true);
                        frame.addWindowListener(new WindowAdapter() {
                            @Override
                            public void windowClosing(WindowEvent e) {
                                browser.dispose();
                            }
                        });

                        browser.addDisposeListener(new DisposeListener() {
                            public void onDisposed(DisposeEvent event) {
                                frame.setVisible(false);
                            }
                        });
                    }
                };
            }
        });

        browser.loadURL("http://www.popuptest.com");
    }
}

File Downloads

import com.teamdev.jxbrowser.chromium.Browser;
import com.teamdev.jxbrowser.chromium.BrowserFactory;
import com.teamdev.jxbrowser.chromium.DownloadHandler;
import com.teamdev.jxbrowser.chromium.DownloadItem;
import com.teamdev.jxbrowser.chromium.events.DownloadEvent;
import com.teamdev.jxbrowser.chromium.events.DownloadListener;

import javax.swing.*;
import java.awt.*;

/**
 * The sample demonstrates how to handle file download. To cancel download
 * you must return {@code false} from the
 * {@link DownloadHandler#allowDownload(com.teamdev.jxbrowser.chromium.DownloadItem)}
 * method. To listed for download update events you can register your own
 * {@link com.teamdev.jxbrowser.chromium.events.DownloadListener}.
 */
public class DownloadSample {
    public static void main(String[] args) {
        Browser browser = BrowserFactory.create();

        JFrame frame = new JFrame();
        frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        frame.add(browser.getView().getComponent(), BorderLayout.CENTER);
        frame.setSize(800, 600);
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);

        browser.setDownloadHandler(new DownloadHandler() {
            public boolean allowDownload(DownloadItem download) {
                download.addDownloadListener(new DownloadListener() {
                    public void onDownloadUpdated(DownloadEvent event) {
                        DownloadItem download = event.getDownloadItem();
                        if (download.isCompleted()) {
                            System.out.println("Download is completed!");
                        }
                    }
                });
                System.out.println("Destination file: " +
                        download.getDestinationFile().getAbsolutePath());
                return true;
            }
        });

        browser.loadURL("ftp://ftp.teamdev.com/updates/jxbrowser-4.0-beta.zip");
    }
}

File Upload

import com.teamdev.jxbrowser.chromium.*;

import javax.swing.*;
import java.awt.*;
import java.io.File;

/**
 * The sample demonstrates how to register your DialogHandler and
 * override the functionality that displays file chooser when
 * user uploads file using INPUT TYPE="file" HTML element on a web page.
 */
public class FileUploadSample {
    public static void main(String[] args) {
        Browser browser = BrowserFactory.create();

        JFrame frame = new JFrame();
        frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        frame.add(browser.getView().getComponent(), BorderLayout.CENTER);
        frame.setSize(700, 500);
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);

        browser.setDialogHandler(new SilentDialogHandler() {
            @Override
            public CloseStatus onFileChooser(FileChooserParams params) {
                if (params.getMode() == FileChooserMode.Open) {
                    JFileChooser fileChooser = new JFileChooser();
                    int returnValue = fileChooser.showOpenDialog(
                            params.getBrowser().getView().getComponent());
                    if (returnValue == JFileChooser.APPROVE_OPTION) {
                        File selectedFile = fileChooser.getSelectedFile();
                        params.setSelectedFile(selectedFile.getAbsolutePath());
                        return CloseStatus.OK;
                    }
                }
                return CloseStatus.CANCEL;
            }
        });
        browser.loadURL("http://www.cs.tut.fi/~jkorpela/forms/file.html");
    }
}

Get HTML

import com.teamdev.jxbrowser.chromium.Browser;
import com.teamdev.jxbrowser.chromium.BrowserFactory;
import com.teamdev.jxbrowser.chromium.events.FinishLoadingEvent;
import com.teamdev.jxbrowser.chromium.events.LoadAdapter;

/**
 * This sample demonstrates how to load custom HTML string into
 * Browser component and display it.
 */
public class GetHTMLSample {
    public static void main(String[] args) {
        Browser browser = BrowserFactory.create();
        browser.addLoadListener(new LoadAdapter() {
            @Override
            public void onFinishLoadingFrame(FinishLoadingEvent event) {
                if (event.isMainFrame()) {
                    Browser browser = event.getBrowser();
                    System.out.println("HTML = " + browser.getHTML());
                }
            }
        });
        browser.loadURL("http://www.teamdev.com");
    }
}

DOM Document

import com.teamdev.jxbrowser.chromium.Browser;
import com.teamdev.jxbrowser.chromium.BrowserFactory;
import com.teamdev.jxbrowser.chromium.dom.DOMDocument;
import com.teamdev.jxbrowser.chromium.events.FinishLoadingEvent;
import com.teamdev.jxbrowser.chromium.events.LoadAdapter;

/**
 * This sample demonstrates how to access DOM document of the loaded web page.
 */
public class DOMGetDocumentSample {
    public static void main(String[] args) {
        Browser browser = BrowserFactory.create();
        browser.addLoadListener(new LoadAdapter() {
            @Override
            public void onFinishLoadingFrame(FinishLoadingEvent event) {
                if (event.isMainFrame()) {
                    Browser browser = event.getBrowser();
                    DOMDocument document = browser.getDocument();
                    System.out.println("document = " + document);
                }
            }
        });
        browser.loadURL("http://www.teamdev.com");
    }
}

DOM Elements

import com.teamdev.jxbrowser.chromium.Browser;
import com.teamdev.jxbrowser.chromium.BrowserFactory;
import com.teamdev.jxbrowser.chromium.dom.DOMDocument;
import com.teamdev.jxbrowser.chromium.dom.DOMElement;
import com.teamdev.jxbrowser.chromium.dom.DOMNode;
import com.teamdev.jxbrowser.chromium.dom.DOMNodeType;
import com.teamdev.jxbrowser.chromium.events.FinishLoadingEvent;
import com.teamdev.jxbrowser.chromium.events.LoadAdapter;

import javax.swing.*;
import java.awt.*;
import java.util.List;

/**
 * The sample demonstrates how to use DOM API to get a list of elements
 * with the specific tag name and print their class attribute.
 */
public class DOMGetElementsSample {
    public static void main(String[] args) {
        Browser browser = BrowserFactory.create();

        JFrame frame = new JFrame();
        frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        frame.add(browser.getView().getComponent(), BorderLayout.CENTER);
        frame.setSize(800, 600);
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);

        browser.addLoadListener(new LoadAdapter() {
            @Override
            public void onFinishLoadingFrame(FinishLoadingEvent event) {
                if (event.isMainFrame()) {
                    DOMDocument document = event.getBrowser().getDocument();
                    List<DOMNode> divs = document.getElementsByTagName("div");
                    for (DOMNode div : divs) {
                        if (div.getNodeType() == DOMNodeType.ElementNode) {
                            DOMElement divElement = (DOMElement) div;
                            System.out.println("class = " +
                                    divElement.getAttribute("class"));
                        }
                    }
                }
            }
        });
        browser.loadURL("http://www.google.com");
    }
}

DOM Element Attributes

import com.teamdev.jxbrowser.chromium.Browser;
import com.teamdev.jxbrowser.chromium.BrowserFactory;
import com.teamdev.jxbrowser.chromium.dom.DOMDocument;
import com.teamdev.jxbrowser.chromium.dom.DOMElement;
import com.teamdev.jxbrowser.chromium.events.FinishLoadingEvent;
import com.teamdev.jxbrowser.chromium.events.LoadAdapter;

import javax.swing.*;
import java.awt.*;
import java.util.Map;

/**
 * Demonstrates how to get list of existing attributes of a specified HTML element.
 */
public class DOMGetAttributesSample {
    public static void main(String[] args) {
        Browser browser = BrowserFactory.create();

        JFrame frame = new JFrame();
        frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        frame.add(browser.getView().getComponent(), BorderLayout.CENTER);
        frame.setSize(800, 600);
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);

        browser.addLoadListener(new LoadAdapter() {
            @Override
            public void onFinishLoadingFrame(FinishLoadingEvent event) {
                if (event.isMainFrame()) {
                    DOMDocument document = event.getBrowser().getDocument();
                    DOMElement link = document.getElementById("link");
                    Map<String, String> attributes = link.getAttributes();
                    for (String attrName : attributes.keySet()) {
                        System.out.println(attrName + " = " + attributes.get(attrName));
                    }
                }
            }
        });
        browser.loadHTML("<html><body><a href='#' id='link' title='link title'></a></body></html>");
    }
}

DOM Create Element & Text Node

import com.teamdev.jxbrowser.chromium.Browser;
import com.teamdev.jxbrowser.chromium.BrowserFactory;
import com.teamdev.jxbrowser.chromium.dom.DOMDocument;
import com.teamdev.jxbrowser.chromium.dom.DOMElement;
import com.teamdev.jxbrowser.chromium.dom.DOMNode;
import com.teamdev.jxbrowser.chromium.events.FinishLoadingEvent;
import com.teamdev.jxbrowser.chromium.events.LoadAdapter;

import javax.swing.*;
import java.awt.*;

/**
 * This sample demonstrates how to create a new Paragraph DOM element with custom text and append it in the document.
 */
public class DOMCreateElementSample {
    public static void main(String[] args) {
        Browser browser = BrowserFactory.create();

        JFrame frame = new JFrame();
        frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        frame.getContentPane().add(browser.getView().getComponent(), BorderLayout.CENTER);
        frame.setSize(800, 600);
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);

        browser.addLoadListener(new LoadAdapter() {
            @Override
            public void onFinishLoadingFrame(FinishLoadingEvent event) {
                DOMDocument document = event.getBrowser().getDocument();
                DOMElement root = document.getElementById("root");
                DOMNode textNode = document.createTextNode("Some text");
                DOMElement paragraph = document.createElement("p");
                paragraph.appendChild(textNode);
                root.appendChild(paragraph);
            }
        });
        browser.loadHTML("<html><body><div id='root'></div></body></html>");
    }
}

DOM Events

import com.teamdev.jxbrowser.chromium.Browser;
import com.teamdev.jxbrowser.chromium.BrowserFactory;
import com.teamdev.jxbrowser.chromium.dom.DOMDocument;
import com.teamdev.jxbrowser.chromium.dom.DOMElement;
import com.teamdev.jxbrowser.chromium.dom.events.DOMEvent;
import com.teamdev.jxbrowser.chromium.dom.events.DOMEventListener;
import com.teamdev.jxbrowser.chromium.dom.events.DOMEventType;
import com.teamdev.jxbrowser.chromium.events.LoadAdapter;
import com.teamdev.jxbrowser.chromium.events.LoadEvent;

import javax.swing.*;
import java.awt.*;

/**
 * The sample demonstrates how to register DOM onclick event listener
 * to receive notifications about all mouse click events on the document.
 */
public class DOMEventsSample {
    public static void main(String[] args) {
        Browser browser = BrowserFactory.create();

        JFrame frame = new JFrame();
        frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        frame.add(browser.getView().getComponent(), BorderLayout.CENTER);
        frame.setSize(800, 600);
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);

        browser.addLoadListener(new LoadAdapter() {
            @Override
            public void onDocumentLoadedInMainFrame(LoadEvent event) {
                DOMDocument document = event.getBrowser().getDocument();
                DOMElement documentElement = document.getDocumentElement();
                documentElement.addEventListener(DOMEventType.OnClick, new DOMEventListener() {
                    public void handleEvent(DOMEvent event) {
                        DOMEventType eventType = event.getType();
                        System.out.println("handleEvent = " + eventType);
                    }
                }, false);
            }
        });
        browser.loadURL("http://www.teamdev.com");
    }
}

DOM Simulate Click

import com.teamdev.jxbrowser.chromium.Browser;
import com.teamdev.jxbrowser.chromium.BrowserFactory;
import com.teamdev.jxbrowser.chromium.dom.DOMDocument;
import com.teamdev.jxbrowser.chromium.dom.DOMElement;
import com.teamdev.jxbrowser.chromium.events.FinishLoadingEvent;
import com.teamdev.jxbrowser.chromium.events.LoadAdapter;

import javax.swing.*;
import javax.swing.text.html.HTML;
import java.awt.*;

/**
 * This sample demonstrates how to simulate click on a specific HTML element.
 */
public class DOMSimulateClickSample {
    public static void main(String[] args) {
        Browser browser = BrowserFactory.create();

        JFrame frame = new JFrame();
        frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        frame.add(browser.getView().getComponent(), BorderLayout.CENTER);
        frame.setSize(800, 600);
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);

        browser.addLoadListener(new LoadAdapter() {
            @Override
            public void onFinishLoadingFrame(FinishLoadingEvent event) {
                if (event.isMainFrame()) {
                    Browser browser = event.getBrowser();
                    DOMDocument document = browser.getDocument();
                    DOMElement link = document.getElementById("button");
                    if (link != null) {
                        link.click();
                    }
                }
            }
        });
        browser.loadHTML("<html><body><button id='button' " +
                "onclick=\"alert('Button has been clicked!');\">Click Me!</button>" +
                "</body></html>");
    }
}

DOM Set Node Value

import com.teamdev.jxbrowser.chromium.Browser;
import com.teamdev.jxbrowser.chromium.BrowserFactory;
import com.teamdev.jxbrowser.chromium.dom.DOMDocument;
import com.teamdev.jxbrowser.chromium.dom.DOMElement;
import com.teamdev.jxbrowser.chromium.events.FinishLoadingEvent;
import com.teamdev.jxbrowser.chromium.events.LoadAdapter;

import javax.swing.*;
import java.awt.*;

/**
 * The sample demonstrates how to use DOMNode.setNodeValue() method.
 */
public class DOMSetNodeValueSample {
    public static void main(String[] args) {
        Browser browser = BrowserFactory.create();

        JFrame frame = new JFrame();
        frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        frame.add(browser.getView().getComponent(), BorderLayout.CENTER);
        frame.setSize(800, 600);
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);

        browser.addLoadListener(new LoadAdapter() {
            @Override
            public void onFinishLoadingFrame(FinishLoadingEvent event) {
                if (event.isMainFrame()) {
                    DOMDocument document = event.getBrowser().getDocument();
                    DOMElement button = document.getElementById("button-id");
                    button.getChildren().get(0).setNodeValue("New Button Name");
                }
            }
        });
        browser.loadHTML("<html><body><button id='button-id'>Button</button></body></html>");
    }
}

DOM Query Selector

import com.teamdev.jxbrowser.chromium.Browser;
import com.teamdev.jxbrowser.chromium.BrowserFactory;
import com.teamdev.jxbrowser.chromium.dom.DOMDocument;
import com.teamdev.jxbrowser.chromium.dom.DOMElement;
import com.teamdev.jxbrowser.chromium.dom.DOMNode;
import com.teamdev.jxbrowser.chromium.events.FinishLoadingEvent;
import com.teamdev.jxbrowser.chromium.events.LoadAdapter;

import javax.swing.*;
import java.awt.*;
import java.util.List;

/**
 * This sample demonstrates how to use querySelector DOM API.
 */
public class DOMQuerySelectorSample {
    public static void main(String[] args) {
        Browser browser = BrowserFactory.create();

        JFrame frame = new JFrame();
        frame.getContentPane().add(browser.getView().getComponent(), BorderLayout.CENTER);
        frame.setSize(800, 600);
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);

        browser.addLoadListener(new LoadAdapter() {
            @Override
            public void onFinishLoadingFrame(FinishLoadingEvent event) {
                DOMDocument document = event.getBrowser().getDocument();
                DOMElement documentElement = document.getDocumentElement();
                // Get the div with id = "root".
                DOMNode divRoot = documentElement.querySelector("#root");
                // Get all paragraphs.
                List<DOMNode> paragraphs = divRoot.querySelectorAll("p");
                for (DOMNode paragraph : paragraphs) {
                    System.out.println("paragraph.getNodeValue() = " +
                            paragraph.getNodeValue());
                }
            }
        });
        browser.loadHTML(
                "<html><body><div id='root'>" +
                "<p>paragraph1</p>" +
                "<p>paragraph2</p>" +
                "<p>paragraph3</p>" +
                "</div></body></html>");
    }
}

DOM Select Option

import com.teamdev.jxbrowser.chromium.Browser;
import com.teamdev.jxbrowser.chromium.BrowserFactory;
import com.teamdev.jxbrowser.chromium.dom.DOMDocument;
import com.teamdev.jxbrowser.chromium.dom.DOMElement;
import com.teamdev.jxbrowser.chromium.dom.DOMNode;
import com.teamdev.jxbrowser.chromium.events.FinishLoadingEvent;
import com.teamdev.jxbrowser.chromium.events.LoadAdapter;

import javax.swing.*;
import java.awt.*;
import java.util.*;
import java.util.List;

/**
 * The sample demonstrates how to programatically select an option item in SELECT tag.
 */
public class DOMSelectOption {
    public static void main(String[] args) {
        Browser browser = BrowserFactory.create();

        JFrame frame = new JFrame();
        frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        frame.add(browser.getView().getComponent(), BorderLayout.CENTER);
        frame.setSize(700, 500);
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);

        browser.addLoadListener(new LoadAdapter() {
            @Override
            public void onFinishLoadingFrame(FinishLoadingEvent event) {
                if (event.isMainFrame()) {
                    DOMDocument document = event.getBrowser().getDocument();
                    DOMElement select = document.getElementById("select-tag");
                    selectOptionByIndex(select, 2);
                }
            }
        });
        browser.loadHTML("<html><body><select id='select-tag'>\n" +
                "  <option value=\"volvo\">Volvo</option>\n" +
                "  <option value=\"saab\">Saab</option>\n" +
                "  <option value=\"opel\">Opel</option>\n" +
                "  <option value=\"audi\">Audi</option>\n" +
                "</select></body></html>");
    }

    private static void selectOptionByIndex(DOMElement selectElement, int index) {
        List<DOMNode> children = selectElement.getChildren();
        List<DOMElement> options = new ArrayList<DOMElement>();
        for (DOMNode child : children) {
            if (child instanceof DOMElement) {
                options.add((DOMElement) child);
            }
        }
        DOMElement option = options.get(index);
        option.setAttribute("selected", "selected");
    }
}

JavaScript

import com.teamdev.jxbrowser.chromium.Browser;
import com.teamdev.jxbrowser.chromium.BrowserFactory;
import com.teamdev.jxbrowser.chromium.JSValue;

import javax.swing.*;
import java.awt.*;

/**
 * This sample demonstrates two techniques to execute JavaScript code
 * on the loaded web page: without return value and with return value.
 */
public class JavaScriptSample {
    public static void main(String[] args) {
        Browser browser = BrowserFactory.create();

        JFrame frame = new JFrame();
        frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        frame.add(browser.getView().getComponent(), BorderLayout.CENTER);
        frame.setSize(700, 500);
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);

        // Executes the passed JavaScript code asynchronously.
        browser.executeJavaScript("document.write('<html><title>" +
                "My Title</title><body>Hello from JxBrowser!</body></html>');");

        // Executes the passed JavaScript code and returns the result value.
        JSValue documentTitle = browser.executeJavaScriptAndReturnValue("document.title");
        // Make sure that result value is a string and read its value
        if (documentTitle.isString()) {
            System.out.println("Document Title = " + documentTitle.getString());
        }
    }
}

JavaScript Dialogs

import com.teamdev.jxbrowser.chromium.Browser;
import com.teamdev.jxbrowser.chromium.BrowserFactory;
import com.teamdev.jxbrowser.chromium.DefaultDialogHandler;
import com.teamdev.jxbrowser.chromium.DialogParams;

import javax.swing.*;
import java.awt.*;

/**
 * The sample demonstrates how to override default alert dialog. You
 * can register your own DialogHandler where you can implement all
 * the required JavaScript dialogs yourself.
 */
public class JavaScriptDialogsSample {
    public static void main(String[] args) {
        Browser browser = BrowserFactory.create();

        JFrame frame = new JFrame();
        frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        frame.add(browser.getView().getComponent(), BorderLayout.CENTER);
        frame.setSize(800, 600);
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);

        browser.setDialogHandler(new DefaultDialogHandler() {
            @Override
            public void onAlert(DialogParams params) {
                String title = "My Alert Dialog";
                String message = params.getMessage();
                JComponent component = params.getBrowser().getView().getComponent();
                JOptionPane.showMessageDialog(component, message, title,
                        JOptionPane.PLAIN_MESSAGE);
            }
        });

        browser.executeJavaScript("alert('test');");
    }
}

JavaScript-Java Bridge

import com.teamdev.jxbrowser.chromium.Browser;
import com.teamdev.jxbrowser.chromium.BrowserFactory;
import com.teamdev.jxbrowser.chromium.BrowserFunction;
import com.teamdev.jxbrowser.chromium.JSValue;
import com.teamdev.jxbrowser.chromium.events.FinishLoadingEvent;
import com.teamdev.jxbrowser.chromium.events.LoadAdapter;

/**
 * The sample demonstrates how to register a new JavaScript function and
 * map it to a Java method that will be invoked every time when the JavaScript
 * function is invoked.
 */
public class JavaScriptJavaSample {
    public static void main(String[] args) {
        Browser browser = BrowserFactory.create();
        browser.registerFunction("MyFunction", new BrowserFunction() {
            public JSValue invoke(JSValue... args) {
                for (JSValue arg : args) {
                    System.out.println("arg = " + arg);
                }
                return JSValue.create("Hello!");
            }
        });
        browser.addLoadListener(new LoadAdapter() {
            @Override
            public void onFinishLoadingFrame(FinishLoadingEvent event) {
                if (event.isMainFrame()) {
                    Browser browser = event.getBrowser();
                    JSValue returnValue = browser.executeJavaScriptAndReturnValue(
                            "MyFunction('Hello JxBrowser!', 1, 2, 3, true);");
                    System.out.println("return value = " + returnValue);
                }
            }
        });
        browser.loadURL("about:blank");
    }
}

Proxy

import com.teamdev.jxbrowser.chromium.*;

/**
 * The sample demonstrates how to configure Browser instance to use custom proxy settings.
 * By default Browser instance uses system proxy settings.
 */
public class ProxySample {
    public static void main(String[] args) {
        // Browser will use system proxy settings.
        // Browser browser = BrowserFactory.create();

        // Browser will automatically detect proxy settings.
        // Browser browser = BrowserFactory.create(new AutoDetectProxyConfig());

        // Browser will not use a proxy server.
        // Browser browser = BrowserFactory.create(new DirectProxyConfig());

        // Browser will use proxy settings received from proxy auto-config (PAC) file.
        // Browser browser = BrowserFactory.create(new URLProxyConfig("<pac-file-url>"));

        // Browser will use custom user's proxy settings.
        HostPortPair httpServer = new HostPortPair("http-proxy-server", 80);
        HostPortPair httpsServer = new HostPortPair("https-proxy-server", 80);
        HostPortPair ftpServer = new HostPortPair("ftp-proxy-server", 80);
        String exceptions = "<local>";  // bypass proxy server for local web pages

        Browser browser = BrowserFactory.create(new CustomProxyConfig(httpServer,
                httpsServer, ftpServer, exceptions));

        // In order to handle proxy authorization you can use the following way
        browser.getContext().setNetworkDelegate(new DefaultNetworkDelegate() {
            @Override
            public boolean onAuthRequired(AuthRequiredParams params) {
                if (params.isProxy()) {
                    params.setUsername("proxy-username");
                    params.setPassword("proxy-password");
                    return false;
                }
                return true;
            }
        });
    }
}

HTML to PNG Image

import com.teamdev.jxbrowser.chromium.Browser;
import com.teamdev.jxbrowser.chromium.BrowserFactory;
import com.teamdev.jxbrowser.chromium.BrowserView;
import com.teamdev.jxbrowser.chromium.events.FinishLoadingEvent;
import com.teamdev.jxbrowser.chromium.events.LoadAdapter;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;

/**
 * The sample demonstrates how to get screen shot of the web page
 * and save it as PNG image file.
 */
public class HTMLToImageSample {
    public static void main(String[] args) throws Exception {
        final Browser browser = BrowserFactory.create();
        // Wait until web page is loaded completely
        invokeAndWaitReady(browser, new Runnable() {
            public void run() {
                browser.loadURL("http://www.teamdev.com");
            }
        });

        int viewWidth = 1280;
        int viewHeight = 1024;
        BrowserView view = browser.getView();
        // Resize view to the required size
        view.updateSize(viewWidth, viewHeight);
        // Get image of the loaded web page
        Image image = view.getImage();
        // Save image as PNG file
        BufferedImage bufferedImage = new BufferedImage(viewWidth, viewHeight,
                BufferedImage.TYPE_4BYTE_ABGR);
        bufferedImage.getGraphics().drawImage(image, 0, 0, null);
        ImageIO.write(bufferedImage, "PNG", new File("teamdev.com.png"));
        browser.dispose();
    }

    public static void invokeAndWaitReady(Browser browser, Runnable runnable) {
        final CountDownLatch latch = new CountDownLatch(1);
        LoadAdapter listener = new LoadAdapter() {
            @Override
            public void onFinishLoadingFrame(FinishLoadingEvent event) {
                if (event.isMainFrame()) {
                    latch.countDown();
                }
            }
        };
        browser.addLoadListener(listener);
        try {
            runnable.run();
            try {
                if (!latch.await(45, TimeUnit.SECONDS)) {
                    throw new RuntimeException(new TimeoutException());
                }
            } catch (InterruptedException ignore) {
                Thread.currentThread().interrupt();
            }
        } finally {
            browser.removeLoadListener(listener);
        }
    }
}

Restore Browser

import com.teamdev.jxbrowser.chromium.Browser;
import com.teamdev.jxbrowser.chromium.BrowserFactory;
import com.teamdev.jxbrowser.chromium.events.RenderAdapter;
import com.teamdev.jxbrowser.chromium.events.RenderEvent;

import javax.swing.*;
import java.awt.*;

/**
 * This sample demonstrates how to restore Browser instance after its
 * native process unexpectedly terminated. In general to restore
 * Browser instance you just need to load the same or another URL.
 */
public class RestoreBrowserSample {
    public static void main(String[] args) {
        Browser browser = BrowserFactory.create();

        JFrame frame = new JFrame();
        frame.add(browser.getView().getComponent(), BorderLayout.CENTER);
        frame.setSize(800, 600);
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);

        browser.addRenderListener(new RenderAdapter() {
            @Override
            public void onRenderGone(RenderEvent event) {
                Browser browser = event.getBrowser();
                // Restore Browser instance by loading the same URL
                browser.loadURL(browser.getURL());
            }
        });

        browser.loadURL("http://www.google.com");

        System.out.println("Run 'Task Manager' app and kill the 'jxbrowser-chromium.exe' " +
                "process with the '--type=renderer' command line argument.");
    }
}

Dispose Browser

import com.teamdev.jxbrowser.chromium.Browser;
import com.teamdev.jxbrowser.chromium.BrowserFactory;
import com.teamdev.jxbrowser.chromium.events.DisposeEvent;
import com.teamdev.jxbrowser.chromium.events.DisposeListener;

/**
 * This sample demonstrates how to dispose Browser instance.
 * Every Browser instance must be disposed before your Java
 * application exit.
 */
public class DisposeBrowserSample {
    public static void main(String[] args) {
        Browser browser = BrowserFactory.create();
        browser.addDisposeListener(new DisposeListener() {
            public void onDisposed(DisposeEvent event) {
                System.out.println("Browser is disposed.");
            }
        });
        browser.dispose();
    }
}

Context Menu

import com.teamdev.jxbrowser.chromium.Browser;
import com.teamdev.jxbrowser.chromium.BrowserFactory;
import com.teamdev.jxbrowser.chromium.ContextMenuHandler;
import com.teamdev.jxbrowser.chromium.ContextMenuParams;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

/**
 * The sample demonstrates how to register custom ContextMenuHandler,
 * to handle mouse right clicks and display custom Swing context menu.
 */
public class ContextMenuSample {
    public static void main(String[] args) {
        Browser browser = BrowserFactory.create();

        JFrame frame = new JFrame();
        frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        frame.add(browser.getView().getComponent(), BorderLayout.CENTER);
        frame.setSize(700, 500);
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);

        browser.setContextMenuHandler(new MyContextMenuHandler());
        browser.loadURL("http://www.google.com");
    }

    private static JMenuItem createMenuItem(String title, final Runnable action) {
        JMenuItem reloadMenuItem = new JMenuItem(title);
        reloadMenuItem.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                action.run();
            }
        });
        return reloadMenuItem;
    }

    private static class MyContextMenuHandler implements ContextMenuHandler {
        public void showContextMenu(final ContextMenuParams params) {
            final JPopupMenu popupMenu = new JPopupMenu();
            if (!params.getLinkText().isEmpty()) {
                popupMenu.add(createMenuItem("Open link in new window", new Runnable() {
                    public void run() {
                        String linkURL = params.getLinkURL();
                        System.out.println("linkURL = " + linkURL);
                    }
                }));
            }

            final Browser browser = params.getBrowser();
            popupMenu.add(createMenuItem("Reload", new Runnable() {
                public void run() {
                    browser.reload();
                }
            }));

            final JComponent component = browser.getView().getComponent();
            final Point location = params.getLocation();
            SwingUtilities.invokeLater(new Runnable() {
                public void run() {
                    popupMenu.show(component, location.x, location.y);
                }
            });
        }
    }
}

User-Agent

import com.teamdev.jxbrowser.chromium.Browser;
import com.teamdev.jxbrowser.chromium.BrowserFactory;
import com.teamdev.jxbrowser.chromium.BrowserPreferences;

import javax.swing.*;
import java.awt.*;

/**
 * The sample demonstrates how to configure user-agent string
 * for all Browser instances.
 */
public class UserAgentSample {
    public static void main(String[] args) {
        // It's very important to configure user-agent string
        // before any Browser instance is created.
        BrowserPreferences.setUserAgent("My User Agent String");

        Browser browser = BrowserFactory.create();

        JFrame frame = new JFrame();
        frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        frame.add(browser.getView().getComponent(), BorderLayout.CENTER);
        frame.setSize(700, 500);
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);

        browser.loadURL("http://whatsmyuseragent.com/");
    }
}

Cookie

import com.teamdev.jxbrowser.chromium.Browser;
import com.teamdev.jxbrowser.chromium.BrowserFactory;
import com.teamdev.jxbrowser.chromium.Cookie;
import com.teamdev.jxbrowser.chromium.CookieStorage;

import javax.swing.*;
import java.awt.*;
import java.util.List;

/**
 * The sample demonstrates how to access CookieStorage instance to
 * read all the available cookies.
 */
public class CookieSample {
    public static void main(String[] args) {
        Browser browser = BrowserFactory.create();

        JFrame frame = new JFrame();
        frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        frame.add(browser.getView().getComponent(), BorderLayout.CENTER);
        frame.setSize(800, 600);
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);

        CookieStorage cookieStorage = browser.getCookieStorage();
        List<Cookie> cookies = cookieStorage.getAllCookies();
        for (Cookie cookie : cookies) {
            System.out.println("cookie = " + cookie);
        }
    }
}

Zoom

import com.teamdev.jxbrowser.chromium.Browser;
import com.teamdev.jxbrowser.chromium.BrowserFactory;
import com.teamdev.jxbrowser.chromium.events.FinishLoadingEvent;
import com.teamdev.jxbrowser.chromium.events.LoadAdapter;
import com.teamdev.jxbrowser.chromium.events.ZoomEvent;
import com.teamdev.jxbrowser.chromium.events.ZoomListener;

import javax.swing.*;
import java.awt.*;

/**
 * The sample demonstrates how to modify zoom level for a
 * currently loaded web page. Zoom level will be applied to
 * the currently loaded web page only. If you navigate to
 * a different domain, its zoom level will be 100% until you
 * modify it.
 */
public class ZoomSample {
    public static void main(String[] args) {
        Browser browser = BrowserFactory.create();

        JFrame frame = new JFrame();
        frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        frame.add(browser.getView().getComponent(), BorderLayout.CENTER);
        frame.setSize(700, 500);
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);

        // Listen to zoom changed events
        browser.addZoomListener(new ZoomListener() {
            public void onZoomChanged(ZoomEvent event) {
                System.out.println("event.getURL() = " + event.getURL());
                System.out.println("event.getZoomLevel() = " + event.getZoomLevel());
                System.out.println("event.isRemember() = " + event.isRemember());
            }
        });

        // Modify zoom level every time when main frame is loaded.
        browser.addLoadListener(new LoadAdapter() {
            @Override
            public void onFinishLoadingFrame(FinishLoadingEvent event) {
                if (event.isMainFrame()) {
                    event.getBrowser().setZoomLevel(2.0);
                }
            }
        });
        browser.loadURL("http://www.teamdev.com");
    }
}

Flash

import com.teamdev.jxbrowser.chromium.Browser;
import com.teamdev.jxbrowser.chromium.BrowserFactory;

import javax.swing.*;
import java.awt.*;

/**
 * This sample loads a web page with simple Flash content.
 */
public class FlashSample {
    public static void main(String[] args) {
        Browser browser = BrowserFactory.create();

        JFrame frame = new JFrame("Flash Sample");
        frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        frame.add(browser.getView().getComponent(), BorderLayout.CENTER);
        frame.setSize(800, 600);
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);

        browser.loadURL("http://www.webthrower.com/portfolio/narnia.htm");
    }
}

Silverlight

import com.teamdev.jxbrowser.chromium.Browser;
import com.teamdev.jxbrowser.chromium.BrowserFactory;

import javax.swing.*;
import java.awt.*;

/**
 * This sample loads a web page with Silverlight examples, so you
 * can see how JxBrowser displays Silverlight content.
 */
public class SilverlightSample {
    public static void main(String[] args) {
        Browser browser = BrowserFactory.create();

        JFrame frame = new JFrame("Silverlight Sample");
        frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        frame.add(browser.getView().getComponent(), BorderLayout.CENTER);
        frame.setSize(800, 600);
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);

        browser.loadURL("http://demos.telerik.com/silverlight/");
    }
}

Scroll Document

import com.teamdev.jxbrowser.chromium.Browser;
import com.teamdev.jxbrowser.chromium.BrowserFactory;

import javax.swing.*;
import java.awt.*;
import java.util.concurrent.TimeUnit;

/**
 * This sample demonstrates how to scroll document programmatically.
 */
public class ScrollDocumentSample {
    public static void main(String[] args) throws InterruptedException {
        Browser browser = BrowserFactory.create();

        JFrame frame = new JFrame();
        frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        frame.add(browser.getView().getComponent(), BorderLayout.CENTER);
        frame.setSize(600, 500);
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);

        browser.loadURL("http://www.teamdev.com");
        while (browser.isLoading()) {
            TimeUnit.MILLISECONDS.sleep(50);
        }

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

Get Node at Point

import com.teamdev.jxbrowser.chromium.Browser;
import com.teamdev.jxbrowser.chromium.BrowserFactory;
import com.teamdev.jxbrowser.chromium.dom.DOMNodeAtPoint;
import com.teamdev.jxbrowser.chromium.events.FinishLoadingEvent;
import com.teamdev.jxbrowser.chromium.events.LoadAdapter;

import javax.swing.*;
import java.awt.*;

/**
 * This sample demonstrates how to get DOM Node at a specific point on the web page.
 */
public class GetNodeAtPointSample {
    public static void main(String[] args) {
        Browser browser = BrowserFactory.create();

        JFrame frame = new JFrame();
        frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        frame.add(browser.getView().getComponent(), BorderLayout.CENTER);
        frame.setSize(700, 500);
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);

        browser.addLoadListener(new LoadAdapter() {
            @Override
            public void onFinishLoadingFrame(FinishLoadingEvent event) {
                if (event.isMainFrame()) {
                    Browser browser = event.getBrowser();
                    DOMNodeAtPoint nodeAtPoint = browser.getNodeAtPoint(100, 200);
                    System.out.println("nodeAtPoint = " + nodeAtPoint);
                }
            }
        });
        browser.loadURL("http://www.teamdev.com");
    }
}

Mouse Listener

import com.teamdev.jxbrowser.chromium.Browser;
import com.teamdev.jxbrowser.chromium.BrowserFactory;

import javax.swing.*;
import java.awt.*;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;

/**
 * The sample demonstrates how to register MouseListener to Browser component.
 */
public class MouseListenerSample {
    public static void main(String[] args) {
        Browser browser = BrowserFactory.create();

        JFrame frame = new JFrame();
        frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        frame.add(browser.getView().getComponent(), BorderLayout.CENTER);
        frame.setSize(800, 600);
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);

        browser.getView().getComponent().addMouseListener(new MouseAdapter() {
            @Override
            public void mouseClicked(MouseEvent e) {
                System.out.println("e = " + e);
            }
        });

        browser.loadURL("http://www.teamdev.com");
    }
}

Key Listener

import com.teamdev.jxbrowser.chromium.Browser;
import com.teamdev.jxbrowser.chromium.BrowserFactory;

import javax.swing.*;
import java.awt.*;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;

/**
 * The sample demonstrates how to register KeyListener to Browser component.
 */
public class KeyListenerSample {
    public static void main(String[] args) {
        Browser browser = BrowserFactory.create();

        JFrame frame = new JFrame();
        frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        frame.add(browser.getView().getComponent(), BorderLayout.CENTER);
        frame.setSize(800, 600);
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);

        browser.getView().getComponent().addKeyListener(new KeyAdapter() {
            @Override
            public void keyPressed(KeyEvent e) {
                System.out.println("e = " + e);
            }
        });

        browser.loadURL("http://www.teamdev.com");
    }
}

Key Filter

import com.teamdev.jxbrowser.chromium.Browser;
import com.teamdev.jxbrowser.chromium.BrowserFactory;
import com.teamdev.jxbrowser.chromium.KeyFilter;

import javax.swing.*;
import java.awt.*;
import java.awt.event.KeyEvent;

/**
 * This sample demonstrates how to register key filter to filter
 * Ctrl+A key events to prevent text selection.
 */
public class KeyFilterSample {
    public static void main(String[] args) {
        Browser browser = BrowserFactory.create();

        JFrame frame = new JFrame();
        frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        frame.add(browser.getView().getComponent(), BorderLayout.CENTER);
        frame.setSize(700, 500);
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);

        browser.getView().setKeyFilter(new KeyFilter() {
            public boolean filter(KeyEvent event) {
                return event.isControlDown() && event.getKeyCode() == KeyEvent.VK_A;
            }
        });
        browser.loadURL("http://www.teamdev.com");
    }
}

Console Events

import com.teamdev.jxbrowser.chromium.Browser;
import com.teamdev.jxbrowser.chromium.BrowserFactory;
import com.teamdev.jxbrowser.chromium.events.ConsoleEvent;
import com.teamdev.jxbrowser.chromium.events.ConsoleListener;

import javax.swing.*;
import java.awt.*;

/**
 * The sample demonstrates how to listen to console messages including
 * JavaScript errors.
 */
public class ConsoleListenerSample {
    public static void main(String[] args) {
        Browser browser = BrowserFactory.create();

        JFrame frame = new JFrame();
        frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        frame.add(browser.getView().getComponent(), BorderLayout.CENTER);
        frame.setSize(700, 500);
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);

        browser.addConsoleListener(new ConsoleListener() {
            public void onMessage(ConsoleEvent event) {
                System.out.println("Level: " + event.getLevel());
                System.out.println("Message: " + event.getMessage());
            }
        });
        browser.executeJavaScript("console.error(\"Error message\");");
    }
}

JInternalFrame

import com.teamdev.jxbrowser.chromium.Browser;
import com.teamdev.jxbrowser.chromium.BrowserFactory;

import javax.swing.*;
import java.awt.*;

/**
 * The sample demonstrates how to use Browser in JInternalFrame components.
 */
public class JInternalFrameSample {
    public static void main(String[] args) {
        JDesktopPane desktopPane = new JDesktopPane();
        desktopPane.add(createInternalFrame("Browser One", "http://www.teamdev.com", 0));
        desktopPane.add(createInternalFrame("Browser Two", "http://www.google.com", 100));

        JFrame frame = new JFrame();
        frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        frame.add(desktopPane, BorderLayout.CENTER);
        frame.setSize(800, 800);
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);
    }

    private static JInternalFrame createInternalFrame(String title, String url, int offset) {
        Browser browser = BrowserFactory.create();
        browser.loadURL(url);

        JInternalFrame internalFrame = new JInternalFrame(title, true);
        internalFrame.setContentPane(browser.getView().getComponent());
        internalFrame.setLocation(100 + offset, 100 + offset);
        internalFrame.setSize(400, 400);
        internalFrame.setVisible(true);
        return internalFrame;
    }
}

Google Maps

import com.teamdev.jxbrowser.chromium.Browser;
import com.teamdev.jxbrowser.chromium.BrowserFactory;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

/**
 * This sample demonstrates how to load a web page with Google Maps
 * and control it using JxBrowser API.
 */
public class GoogleMapsSample {

    public static final int MIN_ZOOM = 0;
    public static final int MAX_ZOOM = 21;

    /**
     * In map.html file default zoom value is set to 4.
     */
    private static int zoomValue = 4;

    public static void main(String[] args) {
        final Browser browser = BrowserFactory.create();

        JButton zoomInButton = new JButton("Zoom In");
        zoomInButton.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                if (zoomValue < MAX_ZOOM) {
                    browser.executeJavaScript("map.setZoom(" + ++zoomValue + ")");
                }
            }
        });

        JButton zoomOutButton = new JButton("Zoom Out");
        zoomOutButton.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                if (zoomValue > MIN_ZOOM) {
                    browser.executeJavaScript("map.setZoom(" + --zoomValue + ")");
                }
            }
        });

        JPanel toolBar = new JPanel();
        toolBar.add(zoomInButton);
        toolBar.add(zoomOutButton);

        JFrame frame = new JFrame();
        frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        frame.add(browser.getView().getComponent(), BorderLayout.CENTER);
        frame.add(toolBar, BorderLayout.SOUTH);
        frame.setSize(900, 500);
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);

        browser.loadURL("map.html");
    }
}

Where the map.html file has the following content:

<!DOCTYPE html>
<html>
  <head>
    <meta name="viewport" content="initial-scale=1.0, user-scalable=no" />
    <style type="text/css">
      html { height: 100% }
      body { height: 100%; margin: 0; padding: 0 }
      #map-canvas { height: 100% }
    </style>
    <script type="text/javascript"
      src="https://maps.googleapis.com/maps/api/js?key=AIzaSyB7J1zsErb9_7jxNu5KU5kIENFObAQEbl0&sensor=false">
    </script>
    <script type="text/javascript">
      var map;
      function initialize() {
        var mapOptions = {
          center: new google.maps.LatLng(48.209331, 16.381302),
          zoom: 4
        };
        map = new google.maps.Map(document.getElementById("map-canvas"),
            mapOptions);
      }
      google.maps.event.addDomListener(window, 'load', initialize);
    </script>
  </head>
  <body>
    <div id="map-canvas"/>
  </body>
</html>

Save Web Page

import com.teamdev.jxbrowser.chromium.Browser;
import com.teamdev.jxbrowser.chromium.BrowserFactory;
import com.teamdev.jxbrowser.chromium.SavePageType;
import com.teamdev.jxbrowser.chromium.events.FinishLoadingEvent;
import com.teamdev.jxbrowser.chromium.events.LoadAdapter;

import javax.swing.*;
import java.awt.*;

/**
 * This sample demonstrates how to save the loaded web page.
 */
public class SaveWebPageSample {
    public static void main(String[] args) {
        Browser browser = BrowserFactory.create();

        JFrame frame = new JFrame();
        frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        frame.add(browser.getView().getComponent(), BorderLayout.CENTER);
        frame.setSize(700, 500);
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);

        browser.addLoadListener(new LoadAdapter() {
            @Override
            public void onFinishLoadingFrame(FinishLoadingEvent event) {
                if (event.isMainFrame()) {
                    String filePath = "D:\\Test\\index.html";
                    String dirPath = "D:\\Test\\resources";
                    event.getBrowser().saveWebPage(filePath, dirPath, SavePageType.COMPLETE_HTML);
                }
            }
        });

        browser.loadURL("http://www.google.com");
    }
}

Browser Context

import com.teamdev.jxbrowser.chromium.Browser;
import com.teamdev.jxbrowser.chromium.BrowserContext;
import com.teamdev.jxbrowser.chromium.BrowserFactory;

import java.io.File;

/**
 * By default all Browser instances created via BrowserFactory.create() method share
 * cookies and cache data. This sample demonstrates how to create two totally isolated
 * Browser instances that don't share cookies and cache data.
 */
public class BrowserContextSample {
    public static void main(String[] args) {
        // This Browser instance will store cookies and user data files in "user-data-dir-one" dir.
        String browserOneUserDataDir = new File("user-data-dir-one").getAbsolutePath();
        Browser browserOne = BrowserFactory.create(new BrowserContext(browserOneUserDataDir));

        // This Browser instance will store cookies and user data files in "user-data-dir-two" dir.
        String browserTwoUserDataDir = new File("user-data-dir-two").getAbsolutePath();
        Browser browserTwo = BrowserFactory.create(new BrowserContext(browserTwoUserDataDir));

        // The browserOne and browserTwo will not see the cookies and cache data files of each other.
    }
}

Status Listener

import com.teamdev.jxbrowser.chromium.Browser;
import com.teamdev.jxbrowser.chromium.BrowserFactory;
import com.teamdev.jxbrowser.chromium.LoggerProvider;
import com.teamdev.jxbrowser.chromium.events.StatusEvent;
import com.teamdev.jxbrowser.chromium.events.StatusListener;
import com.teamdev.jxbrowser.chromium.events.TitleEvent;
import com.teamdev.jxbrowser.chromium.events.TitleListener;

import javax.swing.*;
import java.awt.*;
import java.util.logging.Level;

/**
 * The sample demonstrates how to listen to status change events.
 */
public class StatusListenerSample {
    public static void main(String[] args) {
        LoggerProvider.getIPCLogger().setLevel(Level.SEVERE);
        Browser browser = BrowserFactory.create();

        JFrame frame = new JFrame();
        frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        frame.add(browser.getView().getComponent(), BorderLayout.CENTER);
        frame.setSize(800, 600);
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);

        browser.addStatusListener(new StatusListener() {
            public void onStatusChange(StatusEvent event) {
                System.out.println("Text = " + event.getText());
            }
        });

        browser.loadURL("http://www.google.com");
    }
}

Execute jQuery

import com.teamdev.jxbrowser.chromium.Browser;
import com.teamdev.jxbrowser.chromium.BrowserFactory;
import com.teamdev.jxbrowser.chromium.events.FinishLoadingEvent;
import com.teamdev.jxbrowser.chromium.events.LoadAdapter;

import javax.swing.*;
import java.awt.*;

/**
 * The sample demonstrates how to execute jQuery code on the loaded
 * web page using JxBrowser API.
 */
public class JQuerySample {
    public static void main(String[] args) {
        Browser browser = BrowserFactory.create();

        JFrame frame = new JFrame();
        frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        frame.add(browser.getView().getComponent(), BorderLayout.CENTER);
        frame.setSize(800, 600);
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);

        browser.addLoadListener(new LoadAdapter() {
            @Override
            public void onFinishLoadingFrame(FinishLoadingEvent event) {
                if (event.isMainFrame()) {
                    // Hide all paragraphs using JQuery
                    event.getBrowser().executeJavaScript("$('p').hide();");
                }
            }
        });
        // Load local index.html file that uses local jquery.min.js. Path
        // to the local jquery.min.js file must be relative.
        browser.loadURL("d:\\index.html");
    }
}

The index.html file has the following content:

<!DOCTYPE html>
<html>
<head>
<script src="jquery.min.js"></script>
</head>

<body>
<p>This is a paragraph.</p>
<p>This is another paragraph.</p>
</body>
</html>

Please note that this example requires the jquery.min.js file is located in the same directory where the index.html file is located. You can download jquery.min.js file at http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js

Clear Cache

import com.teamdev.jxbrowser.chromium.Browser;
import com.teamdev.jxbrowser.chromium.BrowserContext;
import com.teamdev.jxbrowser.chromium.BrowserFactory;

/**
 * This sample demonstrates how to clear the Browser's cache. If you create
 * several browser instances by calling BrowserFactory.create() or
 * BrowserFactory.create(BrowserContext context) method using the same
 * BrowserContext instance, calling CacheStorage.clearCache()
 * will remove cache for all these browser instances.
 */
public class ClearCacheSample {
    public static void main(String[] args) {
        BrowserContext context1 = new BrowserContext("C:\\my-data1");
        Browser browser1 = BrowserFactory.create(context1);
        Browser browser2 = BrowserFactory.create(context1);

        BrowserContext context2 = new BrowserContext("C:\\my-data2");
        Browser browser3 = BrowserFactory.create(context2);

        // Clears cache of browser1 and browser2 instances because they use the same
        // user data and cache "C:\\my-data1" directory. It doesn't clear cache
        // of browser3, because browser3 uses a different directory for storing
        // cache data - "C:\\my-data2".
        browser1.getCacheStorage().clearCache();
    }
}

Disable Drag&Drop

import com.teamdev.jxbrowser.chromium.Browser;
import com.teamdev.jxbrowser.chromium.BrowserFactory;

import javax.swing.*;
import java.awt.*;

/**
 * The sample demonstrates how to disable functionality that allows dragging
 * links from the loaded web page.
 */
public class DisableDragAndDropSample {
    public static void main(String[] args) {
        Browser browser = BrowserFactory.create();

        JFrame frame = new JFrame();
        frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        frame.add(browser.getView().getComponent(), BorderLayout.CENTER);
        frame.setSize(800, 600);
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);

        if (browser.getView().isDragAndDropEnabled()) {
            // Now you cannot drag and drop links from the loaded web page.
            browser.getView().setDragAndDropEnabled(false);
        }

        browser.loadURL("http://www.google.com");
    }
}

Execute Command

import com.teamdev.jxbrowser.chromium.Browser;
import com.teamdev.jxbrowser.chromium.BrowserFactory;
import com.teamdev.jxbrowser.chromium.EditorCommand;
import com.teamdev.jxbrowser.chromium.events.FinishLoadingEvent;
import com.teamdev.jxbrowser.chromium.events.LoadAdapter;

import javax.swing.*;
import java.awt.*;

/**
 * This sample demonstrates how to execute Browser commands such as Cut, Copy,
 * Paste, Undo, SelectAll, InsertText etc.
 */
public class ExecuteCommandSample {
    public static void main(String[] args) {
        Browser browser = BrowserFactory.create();

        JFrame frame = new JFrame();
        frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        frame.add(browser.getView().getComponent(), BorderLayout.CENTER);
        frame.setSize(700, 500);
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);

        browser.addLoadListener(new LoadAdapter() {
            @Override
            public void onFinishLoadingFrame(FinishLoadingEvent event) {
                if (event.isMainFrame()) {
                    Browser browser = event.getBrowser();
                    // Inserts "TeamDev" text into Google Search field.
                    browser.executeCommand(EditorCommand.INSERT_TEXT, "JxBrowser");
                    // Inserts a new line into Google Search field to simulate Enter.
                    browser.executeCommand(EditorCommand.INSERT_NEW_LINE);
                }
            }
        });
        browser.loadURL("http://www.google.com");
    }
}

Get Product Version

import com.teamdev.jxbrowser.chromium.ProductInfo;

/**
 * This sample demonstrates how to get JxBrowser version and build.
 */
public class GetProductVersionSample {
    public static void main(String[] args) {
        String name = ProductInfo.getName();
        String version = ProductInfo.getVersion();
        String build = ProductInfo.getBuild();
    }
}

Web Preferences

import com.teamdev.jxbrowser.chromium.Browser;
import com.teamdev.jxbrowser.chromium.BrowserFactory;
import com.teamdev.jxbrowser.chromium.BrowserPreferences;

/**
 * This sample demonstrates how to get and override web preferences.
 */
public class BrowserPreferencesSample {
    public static void main(String[] args) {
        Browser browserOne = BrowserFactory.create();
        // Gets the current Browser's preferences
        BrowserPreferences preferences = browserOne.getPreferences();
        preferences.setImagesEnabled(false);
        preferences.setJavaScriptEnabled(false);
        // Updates Browser's preferences
        browserOne.setPreferences(preferences);

        // Images and JavaScript will be disabled
        browserOne.loadURL("http://www.google.com/");

        // Images and JavaScript will not be disabled
        Browser browserTwo = BrowserFactory.create();
        browserTwo.loadURL("http://www.teamdev.com/");
    }
}

Navigation History

import com.teamdev.jxbrowser.chromium.Browser;
import com.teamdev.jxbrowser.chromium.BrowserFactory;
import com.teamdev.jxbrowser.chromium.NavigationEntry;

import javax.swing.*;
import java.awt.*;

/**
 * The sample demonstrates how to work with Browser's navigation history.
 */
public class HistorySample {
    public static void main(String[] args) {
        Browser browser = BrowserFactory.create();

        JFrame frame = new JFrame();
        frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        frame.add(browser.getView().getComponent(), BorderLayout.CENTER);
        frame.setSize(800, 600);
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);

        // Returns the number of entries in the back/forward list.
        // int entryCount = browser.getNavigationEntryCount();

        // Returns index of the current navigation entry in the back/forward list.
        int index = browser.getCurrentNavigationEntryIndex();

        // Navigates to the entry at a specific index in the back/forward list.
        // browser.goToIndex(index);

        // Removes navigation entry from the back/forward list at a specific index.
        // boolean success = browser.removeNavigationEntryAtIndex(index);

        // Prints 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());

    }
}

Network Delegate

import com.teamdev.jxbrowser.chromium.*;

import javax.swing.*;
import java.awt.*;

/**
 * This sample demonstrates how to use request handler.
 */
public class NetworkDelegateSample {
    public static void main(String[] args) {
        BrowserContext browserContext = BrowserContext.defaultContext();
        browserContext.setNetworkDelegate(new DefaultNetworkDelegate() {
            @Override
            public void onBeforeURLRequest(BeforeURLRequestParams params) {
                // If navigate to teamdev.com, then change URL to google.com.
                if (params.getURL().equals("http://www.teamdev.com/")) {
                    params.setURL("www.google.com");
                }
            }

            @Override
            public void onBeforeSendHeaders(BeforeSendHeadersParams params) {
                // If navigate to google.com, then print User-Agent header value.
                if (params.getURL().equals("http://www.google.com/")) {
                    HttpHeaders headers = params.getHeaders();
                    System.out.println("User-Agent: " + headers.getHeader("User-Agent"));
                }
            }
        });

        Browser browser = BrowserFactory.create(browserContext);

        JFrame frame = new JFrame();
        frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        frame.add(browser.getView().getComponent(), BorderLayout.CENTER);
        frame.setSize(700, 500);
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);

        browser.loadURL("http://www.teamdev.com/");
    }
}

Chrome Developer Tools

import com.teamdev.jxbrowser.chromium.Browser;
import com.teamdev.jxbrowser.chromium.BrowserFactory;
import com.teamdev.jxbrowser.chromium.BrowserPreferences;

import javax.swing.*;
import java.awt.*;

/**
 * This sample demonstrates how to use Chromium remote debugging feature.
 */
public class RemoteDebuggingSample {

    public static void main(String[] args) {
        // Specifies remote debugging port for remote Chrome Developer Tools.
        BrowserPreferences.setChromiumSwitches("--remote-debugging-port=9222");

        Browser browser1 = BrowserFactory.create();

        // Gets URL of the remote Developer Tools web page for browser1 instance.
        String remoteDebuggingURL = browser1.getRemoteDebuggingURL();

        JFrame frame1 = new JFrame();
        frame1.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        frame1.add(browser1.getView().getComponent(), BorderLayout.CENTER);
        frame1.setSize(700, 500);
        frame1.setLocationRelativeTo(null);
        frame1.setVisible(true);

        browser1.loadURL("http://www.google.com");

        // Creates another Browser instance and loads the remote Developer
        // Tools URL to access HTML inspector.
        Browser browser2 = BrowserFactory.create();

        JFrame frame2 = new JFrame();
        frame2.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        frame2.add(browser2.getView().getComponent(), BorderLayout.CENTER);
        frame2.setSize(700, 500);
        frame2.setLocationRelativeTo(null);
        frame2.setVisible(true);

        browser2.loadURL(remoteDebuggingURL);
    }
}

Calculate Page Dimension

To calculate the document size you can use different approaches. For example, you can calculate page dimension using the following way:

JSValue documentHeight = browser.executeJavaScriptAndReturnValue("Math.max(document.body.scrollHeight, " +
        "document.documentElement.scrollHeight, document.body.offsetHeight, " +
        "document.documentElement.offsetHeight, document.body.clientHeight, " +
        "document.documentElement.clientHeight);");
JSValue documentWidth = browser.executeJavaScriptAndReturnValue("Math.max(document.body.scrollWidth, " +
"document.documentElement.scrollWidth, document.body.offsetWidth, " +
"document.documentElement.offsetWidth, document.body.clientWidth, " + "document.documentElement.clientWidth);"); int scrollBarSize = 25; int viewWidth = (int) documentWidth.getNumber() + scrollBarSize; int viewHeight = (int) documentHeight.getNumber() + scrollBarSize;