Before you start running the following samples you need to configure your Java project. We recommend that you take a look at Quick Start Guide to find out how to use JxBrowser with IntelliJ IDEA, NetBeans and Eclipse.

Browser Swing

import com.teamdev.jxbrowser.chromium.Browser;
import com.teamdev.jxbrowser.chromium.swing.BrowserView;

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

/**
 * This sample demonstrates how to create Browser instance,
 * embed it into Swing BrowserView container, display it in JFrame and
 * navigate to the "www.google.com" web site.
 */
public class BrowserSample {
    public static void main(String[] args) {
        Browser browser = new Browser();
        BrowserView browserView = new BrowserView(browser);

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

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

Browser JavaFX

import com.teamdev.jxbrowser.chromium.Browser;
import com.teamdev.jxbrowser.chromium.javafx.BrowserView;
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.layout.StackPane;
import javafx.stage.Stage;

/**
 * Demonstrates how to embed Browser instance into JavaFX application.
 */
public class JavaFXSample extends Application {

    @Override
    public void start(Stage primaryStage) {
        Browser browser = new Browser();
        BrowserView browserView = new BrowserView(browser);

        StackPane pane = new StackPane();
        pane.getChildren().add(browserView);
        Scene scene = new Scene(pane, 700, 500);
        primaryStage.setScene(scene);
        primaryStage.show();

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

    public static void main(String[] args) {
        launch(args);
    }
}

Load URL

import com.teamdev.jxbrowser.chromium.Browser;
import com.teamdev.jxbrowser.chromium.swing.BrowserView;

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

/**
 * This sample demonstrates how to create Browser instance,
 * embed it into Swing BrowserView container, display it in JFrame and
 * navigate to the "www.google.com" web site.
 */
public class BrowserSample {
    public static void main(String[] args) {
        Browser browser = new Browser();
        BrowserView browserView = new BrowserView(browser);

        JFrame frame = new JFrame();
        frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        frame.add(browserView, 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.events.FinishLoadingEvent;
import com.teamdev.jxbrowser.chromium.events.LoadAdapter;
import com.teamdev.jxbrowser.chromium.swing.BrowserView;

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 = new Browser();
        BrowserView browserView = new BrowserView(browser);

        JFrame frame = new JFrame();
        frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        frame.add(browserView, 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.events.*;
import com.teamdev.jxbrowser.chromium.swing.BrowserView;

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 = new Browser();
        BrowserView browserView = new BrowserView(browser);

        JFrame frame = new JFrame();
        frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        frame.add(browserView, 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) {
                NetError errorCode = event.getErrorCode();
                if (event.isMainFrame()) {
                    System.out.println("Main frame has failed loading: " + errorCode);
                }
            }

            @Override
            public void onDocumentLoadedInFrame(FrameLoadEvent event) {
                System.out.println("Frame document is loaded.");
            }

            @Override
            public void onDocumentLoadedInMainFrame(LoadEvent event) {
                System.out.println("Main frame document is loaded.");
            }
        });

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

Load Handler

import com.teamdev.jxbrowser.chromium.Browser;
import com.teamdev.jxbrowser.chromium.DefaultLoadHandler;
import com.teamdev.jxbrowser.chromium.LoadParams;
import com.teamdev.jxbrowser.chromium.swing.BrowserView;

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 = new Browser();
        BrowserView browserView = new BrowserView(browser);

        JFrame frame = new JFrame();
        frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        frame.add(browserView, 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.Browser;
import com.teamdev.jxbrowser.chromium.Certificate;
import com.teamdev.jxbrowser.chromium.CertificateErrorParams;
import com.teamdev.jxbrowser.chromium.DefaultLoadHandler;
import com.teamdev.jxbrowser.chromium.events.NetError;
import com.teamdev.jxbrowser.chromium.swing.BrowserView;

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

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

        JFrame frame = new JFrame();
        frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        frame.add(browserView, 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.events.TitleEvent;
import com.teamdev.jxbrowser.chromium.events.TitleListener;
import com.teamdev.jxbrowser.chromium.swing.BrowserView;

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 = new Browser();
        BrowserView browserView = new BrowserView(browser);

        JFrame frame = new JFrame();
        frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        frame.add(browserView, 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.Browser;
import com.teamdev.jxbrowser.chromium.PopupContainer;
import com.teamdev.jxbrowser.chromium.PopupHandler;
import com.teamdev.jxbrowser.chromium.PopupParams;
import com.teamdev.jxbrowser.chromium.events.DisposeEvent;
import com.teamdev.jxbrowser.chromium.events.DisposeListener;
import com.teamdev.jxbrowser.chromium.swing.BrowserView;

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 = new Browser();
        final BrowserView browserView = new BrowserView(browser);

        JFrame frame = new JFrame();
        frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        frame.add(browserView, 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) {
                        BrowserView browserView = new BrowserView(browser);
                        browserView.setPreferredSize(initialBounds.getSize());

                        final JFrame frame = new JFrame("Popup");
                        frame.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
                        frame.add(browserView, 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<Browser>() {
                            public void onDisposed(DisposeEvent<Browser> event) {
                                frame.setVisible(false);
                            }
                        });
                    }
                };
            }
        });

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

File Downloads

import com.teamdev.jxbrowser.chromium.Browser;
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 com.teamdev.jxbrowser.chromium.swing.BrowserView;

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 = new Browser();
        BrowserView browserView = new BrowserView(browser);

        JFrame frame = new JFrame();
        frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        frame.add(browserView, 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.Browser;
import com.teamdev.jxbrowser.chromium.CloseStatus;
import com.teamdev.jxbrowser.chromium.FileChooserMode;
import com.teamdev.jxbrowser.chromium.FileChooserParams;
import com.teamdev.jxbrowser.chromium.swing.BrowserView;
import com.teamdev.jxbrowser.chromium.swing.DefaultDialogHandler;

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 = new Browser();
        final BrowserView browserView = new BrowserView(browser);

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

        browser.setDialogHandler(new DefaultDialogHandler(browserView) {
            @Override
            public CloseStatus onFileChooser(FileChooserParams params) {
                if (params.getMode() == FileChooserMode.Open) {
                    JFileChooser fileChooser = new JFileChooser();
                    int returnValue = fileChooser.showOpenDialog(
                            browserView);
                    if (returnValue == JFileChooser.APPROVE_OPTION) {
                        File selectedFile = fileChooser.getSelectedFile();
                        params.setSelectedFiles(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.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 = new Browser();
        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");
    }
}

Get Frame IDs

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

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

/**
 * The sample demonstrates how to get a list of available frame IDs on
 * the loaded web page. Using frame ID parameter you can access document
 * frame to get its HTML, load specified URL in this frame or execute
 * JavaScript on it etc. In this sample we print HTML of each frame.
 */
public class GetFrameIDsSample {
    public static void main(String[] args) {
        Browser browser = new Browser();
        BrowserView browserView = new BrowserView(browser);

        JFrame frame = new JFrame();
        frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        frame.add(browserView, 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();
                    // Get HTML of each frame on the web page
                    Set<Long> framesIds = browser.getFramesIds();
                    for (Long framesId : framesIds) {
                        String html = browser.getHTML(framesId);
                        System.out.println(framesId + " HTML = " + html);
                    }
                }
            }
        });
        browser.loadURL("http://docs.oracle.com/javase/8/docs/api/");
    }
}

DOM Document

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

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

/**
 * This sample demonstrates how to access DOM document of the loaded web page.
 */
public class DOMGetDocumentSample {
    public static void main(String[] args) {
        Browser browser = new Browser();
        BrowserView browserView = new BrowserView(browser);

        JFrame frame = new JFrame();
        frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        frame.getContentPane().add(browserView, 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();
                    System.out.println("document = " + document);
                }
            }
        });
        browser.loadURL("http://www.teamdev.com");
    }
}

DOM Elements

import com.teamdev.jxbrowser.chromium.Browser;
import com.teamdev.jxbrowser.chromium.dom.By;
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 com.teamdev.jxbrowser.chromium.swing.BrowserView;

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 = new Browser();
        BrowserView browserView = new BrowserView(browser);

        JFrame frame = new JFrame();
        frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        frame.add(browserView, 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<DOMElement> divs = document.findElements(By.tagName("div"));
                    for (DOMElement div : divs) {
                        System.out.println("class = " + div.getAttribute("class"));
                    }
                }
            }
        });
        browser.loadURL("http://www.google.com");
    }
}

DOM Element Attributes

import com.teamdev.jxbrowser.chromium.Browser;
import com.teamdev.jxbrowser.chromium.dom.By;
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 com.teamdev.jxbrowser.chromium.swing.BrowserView;

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 = new Browser();
        BrowserView browserView = new BrowserView(browser);

        JFrame frame = new JFrame();
        frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        frame.add(browserView, 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.findElement(By.id("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.dom.By;
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 com.teamdev.jxbrowser.chromium.swing.BrowserView;

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 = new Browser();
        BrowserView browserView = new BrowserView(browser);

        JFrame frame = new JFrame();
        frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        frame.getContentPane().add(browserView, 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();
                DOMNode root = document.findElement(By.id("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.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 com.teamdev.jxbrowser.chromium.swing.BrowserView;

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 = new Browser();
        BrowserView browserView = new BrowserView(browser);

        JFrame frame = new JFrame();
        frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        frame.add(browserView, 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.dom.By;
import com.teamdev.jxbrowser.chromium.dom.DOMDocument;
import com.teamdev.jxbrowser.chromium.dom.DOMNode;
import com.teamdev.jxbrowser.chromium.events.FinishLoadingEvent;
import com.teamdev.jxbrowser.chromium.events.LoadAdapter;
import com.teamdev.jxbrowser.chromium.swing.BrowserView;

import javax.swing.*;
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 = new Browser();
        BrowserView browserView = new BrowserView(browser);

        JFrame frame = new JFrame();
        frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        frame.add(browserView, 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();
                    DOMNode link = document.findElement(By.tagName("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.dom.By;
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 com.teamdev.jxbrowser.chromium.swing.BrowserView;

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 = new Browser();
        BrowserView browserView = new BrowserView(browser);

        JFrame frame = new JFrame();
        frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        frame.add(browserView, 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.findElement(By.id("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.dom.By;
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 com.teamdev.jxbrowser.chromium.swing.BrowserView;

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 = new Browser();
        BrowserView browserView = new BrowserView(browser);

        JFrame frame = new JFrame();
        frame.getContentPane().add(browserView, 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();
                // 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.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.dom.By;
import com.teamdev.jxbrowser.chromium.dom.DOMDocument;
import com.teamdev.jxbrowser.chromium.dom.DOMOptionElement;
import com.teamdev.jxbrowser.chromium.dom.DOMSelectElement;
import com.teamdev.jxbrowser.chromium.events.FinishLoadingEvent;
import com.teamdev.jxbrowser.chromium.events.LoadAdapter;
import com.teamdev.jxbrowser.chromium.swing.BrowserView;

import javax.swing.*;
import java.awt.*;
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 = new Browser();
        BrowserView browserView = new BrowserView(browser);

        JFrame frame = new JFrame();
        frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        frame.add(browserView, 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();
                    DOMSelectElement select = (DOMSelectElement) document.findElement(By.id("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(DOMSelectElement selectElement, int index) {
        List<DOMOptionElement> options = selectElement.getOptions();
        options.get(index).setSelected(true);
    }
}

DOM HTML Form

import com.teamdev.jxbrowser.chromium.Browser;
import com.teamdev.jxbrowser.chromium.dom.By;
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 com.teamdev.jxbrowser.chromium.swing.BrowserView;

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

/**
 * The sample demonstrates how to fill HTML Form fields using JxBrowser DOM API.
 */
public class DOMFormSample {
    public static void main(String[] args) {
        Browser browser = new Browser();
        BrowserView browserView = new BrowserView(browser);

        JFrame frame = new JFrame();
        frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        frame.getContentPane().add(browserView, 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 firstName = document.findElement(By.name("firstName"));
                    firstName.setAttribute("value", "John");
                    DOMElement lastName = document.findElement(By.name("lastName"));
                    lastName.setAttribute("value", "Doe");
                }
            }
        });
        browser.loadHTML("<html><body><form name=\"myForm\">" +
                "First name: <input type=\"text\" name=\"firstName\"/><br/>" +
                "Last name: <input type=\"text\" name=\"lastName\"/><br/>" +
                "<input type=\"button\" value=\"Save\"/>" +
                "</form></body></html>");
    }
}

JavaScript

import com.teamdev.jxbrowser.chromium.Browser;
import com.teamdev.jxbrowser.chromium.JSValue;
import com.teamdev.jxbrowser.chromium.swing.BrowserView;

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 = new Browser();
        BrowserView browserView = new BrowserView(browser);

        JFrame frame = new JFrame();
        frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        frame.add(browserView, 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.DialogParams;
import com.teamdev.jxbrowser.chromium.swing.BrowserView;
import com.teamdev.jxbrowser.chromium.swing.DefaultDialogHandler;

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 = new Browser();
        final BrowserView browserView = new BrowserView(browser);

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

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

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

JavaScript-Java Bridge

import com.teamdev.jxbrowser.chromium.Browser;
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 = new Browser();
        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");
    }
}

JavaScript JObject & JFunction

import com.teamdev.jxbrowser.chromium.Browser;
import com.teamdev.jxbrowser.chromium.JSFunction;
import com.teamdev.jxbrowser.chromium.JSObject;
import com.teamdev.jxbrowser.chromium.JSValue;
import com.teamdev.jxbrowser.chromium.swing.BrowserView;

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

/**
 * The sample demonstrates how to work with JavaScript objects from Java code.
 */
public class JavaScriptObjectsSample {
    public static void main(String[] args) {
        Browser browser = new Browser();
        BrowserView browserView = new BrowserView(browser);

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

        JSValue value = browser.executeJavaScriptAndReturnValue("document");
        if (value.isObject() && value instanceof JSObject) {
            JSObject document = (JSObject) value;
            // Call document.title = "New Document Title";
            boolean success = document.set("title", JSValue.create("New Document Title"));
            System.out.println("Title has been updated successfully: " + success);

            // Call document.write("Hello World!");
            JSValue method = document.get("write");
            if (method.isFunction() && method instanceof JSFunction) {
                JSFunction documentWrite = (JSFunction) method;
                documentWrite.invoke(document, JSValue.create("Hello World!"));
            }
        }
    }
}

JavaScript-Java Bridge Form

import com.teamdev.jxbrowser.chromium.Browser;
import com.teamdev.jxbrowser.chromium.BrowserFunction;
import com.teamdev.jxbrowser.chromium.JSValue;
import com.teamdev.jxbrowser.chromium.swing.BrowserView;

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

/**
 * The sample demonstrates how to send form data from JavaScript to Java.
 */
public class JavaScriptJavaFormSample {
    public static void main(String[] args) {
        Browser browser = new Browser();
        BrowserView browserView = new BrowserView(browser);
        browser.registerFunction("save", new BrowserFunction() {
            public JSValue invoke(JSValue... args) {
                // FirstName is supposed to be first parameter
                JSValue firstNameValue = args[0];
                System.out.println("firstName: " + firstNameValue.getString());

                // FirstName is supposed to be second parameter
                JSValue lastNameValue = args[1];
                System.out.println("lastName: " + lastNameValue.getString());

                return JSValue.createNull();
            }
        });

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

        browser.loadURL("D:\\form.html");
    }
}

Where the form.html file has the following content:

<!DOCTYPE html>
<html>
<head>
    <script type="text/javascript">
          function sendFormData() {
            var firstNameValue = myForm.elements['firstName'].value;
            var lastNameValue = myForm.elements['lastName'].value;
            // Invoke the 'save' Java callback
            save(firstNameValue, lastNameValue);
          }
        </script>
</head>
<body>
<form name="myForm">
    First name: <input type="text" name="firstName"/>
    <br/>
    Last name: <input type="text" name="lastName"/>
    <br/>
    <input type="button" value="Save" onclick="sendFormData();"/>
</form>
</body>
</html>

Proxy

import com.teamdev.jxbrowser.chromium.swing.DefaultNetworkDelegate;
import com.teamdev.jxbrowser.chromium.*;

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

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

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

        // Browser will use proxy settings received from proxy auto-config (PAC) file.
        // Browser browser = new Browser(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 = new Browser(new CustomProxyConfig(httpServer,
                httpsServer, ftpServer, exceptions));

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

POST Data

import com.teamdev.jxbrowser.chromium.*;
import com.teamdev.jxbrowser.chromium.swing.DefaultNetworkDelegate;

/**
 * This sample demonstrates how to read and modify POST parameters using NetworkDelegate.
 */
public class PostDataSample {
    public static void main(String[] args) {
        Browser browser = new Browser();
        BrowserContext browserContext = browser.getContext();
        NetworkService networkService = browserContext.getNetworkService();
        networkService.setNetworkDelegate(new DefaultNetworkDelegate() {
            @Override
            public void onBeforeURLRequest(BeforeURLRequestParams params) {
                if ("POST".equals(params.getMethod())) {
                    PostData post = params.getPostData();
                    PostDataContentType contentType = post.getContentType();
                    if (contentType == PostDataContentType.FORM_URL_ENCODED) {
                        FormData postData = (FormData) post;
                        postData.setPair("key1", "value1", "value2");
                        postData.setPair("key2", "value2");
                    } else if (contentType == PostDataContentType.MULTIPART_FORM_DATA) {
                        MultipartFormData postData = (MultipartFormData) post;
                        postData.setPair("key1", "value1", "value2");
                        postData.setPair("key2", "value2");
                        postData.setFilePair("file3", "C:\\Test.zip");
                    } else if (contentType == PostDataContentType.PLAIN_TEXT) {
                        RawData postData = (RawData) post;
                        postData.setData("raw data");
                    }
                    params.setPostData(post);
                }
            }
        });
        browser.loadURL(new LoadURLParams("http://localhost/", "key=value"));
    }
}

HTML to PNG Image

import com.teamdev.jxbrowser.chromium.Browser;
import com.teamdev.jxbrowser.chromium.Callback;
import com.teamdev.jxbrowser.chromium.swing.BrowserView;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;

/**
 * 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 {
        // #1 Create Browser instance
        Browser browser = new Browser();

        // #2 Set the required view size
        int viewWidth = 1280;
        int viewHeight = 1024;
        BrowserView view = new BrowserView(browser);
        view.setBounds(new Rectangle(viewWidth, viewHeight));

        // #3 Load web page and wait until web page is loaded completely
        Browser.invokeAndWaitFinishLoadingMainFrame(browser, new Callback<Browser>() {
            @Override
            public void invoke(Browser browser) {
                browser.loadURL("http://www.teamdev.com");
            }
        });

        // #4 Get java.awt.Image of the loaded web page.
        Image image = view.getImage();

        // Save image as teamdev.com.png file
        BufferedImage bufferedImage = new BufferedImage(viewWidth, viewHeight,
                BufferedImage.TYPE_4BYTE_ABGR);
        Graphics2D graphics = (Graphics2D) bufferedImage.getGraphics();
        // Scale image according to the current device scale factor.
        // This code must be used to support Retina displays.
        Double scale = 1.0 / view.getDeviceScaleFactor();
        graphics.scale(scale, scale);
        graphics.drawImage(image, 0, 0, null);

        ImageIO.write(bufferedImage, "PNG", new File("teamdev.com.png"));

        // Dispose Browser instance
        browser.dispose();
    }
}

Restore Browser

import com.teamdev.jxbrowser.chromium.Browser;
import com.teamdev.jxbrowser.chromium.events.RenderAdapter;
import com.teamdev.jxbrowser.chromium.events.RenderEvent;
import com.teamdev.jxbrowser.chromium.swing.BrowserView;

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

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

        JFrame frame = new JFrame();
        frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        frame.add(browserView, 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.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 = new Browser();
        browser.addDisposeListener(new DisposeListener<Browser>() {
            public void onDisposed(DisposeEvent<Browser> event) {
                System.out.println("Browser is disposed.");
            }
        });
        browser.dispose();
    }
}

Context Menu

import com.teamdev.jxbrowser.chromium.Browser;
import com.teamdev.jxbrowser.chromium.ContextMenuHandler;
import com.teamdev.jxbrowser.chromium.ContextMenuParams;
import com.teamdev.jxbrowser.chromium.swing.BrowserView;

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 = new Browser();
        BrowserView browserView = new BrowserView(browser);

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

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

    private static class MyContextMenuHandler implements ContextMenuHandler {

        private final JComponent component;

        private MyContextMenuHandler(JComponent parentComponent) {
            this.component = parentComponent;
        }

        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 Point location = params.getLocation();
            SwingUtilities.invokeLater(new Runnable() {
                public void run() {
                    popupMenu.show(component, location.x, location.y);
                }
            });
        }

        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;
        }
    }
}

User-Agent

import com.teamdev.jxbrowser.chromium.Browser;
import com.teamdev.jxbrowser.chromium.BrowserPreferences;
import com.teamdev.jxbrowser.chromium.swing.BrowserView;

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 = new Browser();
        BrowserView browserView = new BrowserView(browser);

        JFrame frame = new JFrame();
        frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        frame.add(browserView, 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.Cookie;
import com.teamdev.jxbrowser.chromium.CookieStorage;
import com.teamdev.jxbrowser.chromium.swing.BrowserView;

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 = new Browser();
        BrowserView browserView = new BrowserView(browser);

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

        CookieStorage cookieStorage = browser.getCookieStorage();

        // Create and add new cookie
        int oneHourInMilliseconds = 36000000;
        int microsecondsOffset = 1000;
        // Cookie will be alive during one hour starting from now
        long expirationTimeInMicroseconds = (System.currentTimeMillis() +
                oneHourInMilliseconds) * microsecondsOffset;
        cookieStorage.setCookie("http://www.google.com", "mycookie", "myvalue",
                ".google.com", "/", expirationTimeInMicroseconds, false, false);

        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.BrowserContext;
import com.teamdev.jxbrowser.chromium.ZoomService;
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 com.teamdev.jxbrowser.chromium.swing.BrowserView;

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 = new Browser();
        BrowserView browserView = new BrowserView(browser);

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

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

        // 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.swing.BrowserView;

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 = new Browser();
        BrowserView browserView = new BrowserView(browser);

        JFrame frame = new JFrame("Flash Sample");
        frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        frame.add(browserView, 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.swing.BrowserView;

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 = new Browser();
        BrowserView browserView = new BrowserView(browser);

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

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

Find Text

import com.teamdev.jxbrowser.chromium.Browser;
import com.teamdev.jxbrowser.chromium.SearchParams;
import com.teamdev.jxbrowser.chromium.SearchResult;
import com.teamdev.jxbrowser.chromium.events.FinishLoadingEvent;
import com.teamdev.jxbrowser.chromium.events.LoadAdapter;
import com.teamdev.jxbrowser.chromium.swing.BrowserView;

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

/**
 * This sample demonstrates, how to find text on the loaded web page.
 */
public class FindTextSample {
    public static void main(String[] args) throws InterruptedException {
        final Browser browser = new Browser();
        BrowserView browserView = new BrowserView(browser);

        JFrame frame = new JFrame();
        frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        frame.add(browserView, 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()) {
                    SearchParams request = new SearchParams("find me");
                    // Find text from the beginning of the loaded web page.
                    SearchResult result = browser.findText(request);
                    System.out.println(result.indexOfSelectedMatch() + "/" + result.getNumberOfMatches());
                    // Find the same text again from the currently selected match.
                    result = browser.findText(request);
                    System.out.println(result.indexOfSelectedMatch() + "/" + result.getNumberOfMatches());
                }
            }
        });
        browser.loadHTML("<html><body><p>Find me</p><p>Find me</p></body></html>");
    }
}

Custom Cursor

import com.teamdev.jxbrowser.chromium.Browser;
import com.teamdev.jxbrowser.chromium.swing.BrowserView;

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

/**
 * The sample demonstrates support of custom CSS cursors.
 */
public class CustomCursorSample {
    public static void main(String[] args) {
        Browser browser = new Browser();
        BrowserView browserView = new BrowserView(browser);

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

        browser.loadHTML("<html><body><a href=\"\" style=\"cursor: " +
                "url(http://www.kyrnin.com/about/redball.cur),default;\">" +
                "cursor: url(redball.cur);</a></body></html>");
    }
}

Scroll Document

import com.teamdev.jxbrowser.chromium.Browser;
import com.teamdev.jxbrowser.chromium.swing.BrowserView;

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 = new Browser();
        BrowserView browserView = new BrowserView(browser);

        JFrame frame = new JFrame();
        frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        frame.add(browserView, 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.dom.DOMNodeAtPoint;
import com.teamdev.jxbrowser.chromium.events.FinishLoadingEvent;
import com.teamdev.jxbrowser.chromium.events.LoadAdapter;
import com.teamdev.jxbrowser.chromium.swing.BrowserView;

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 = new Browser();
        BrowserView browserView = new BrowserView(browser);

        JFrame frame = new JFrame();
        frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        frame.add(browserView, 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.swing.BrowserView;

import javax.swing.*;
import java.awt.*;
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 = new Browser();
        BrowserView browserView = new BrowserView(browser);

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

        browserView.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.swing.BrowserView;

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 = new Browser();
        BrowserView browserView = new BrowserView(browser);

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

        browserView.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.KeyFilter;
import com.teamdev.jxbrowser.chromium.swing.BrowserView;

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 = new Browser();
        BrowserView browserView = new BrowserView(browser);

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

        browserView.setKeyFilter(new KeyFilter<KeyEvent>() {
            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.events.ConsoleEvent;
import com.teamdev.jxbrowser.chromium.events.ConsoleListener;
import com.teamdev.jxbrowser.chromium.swing.BrowserView;

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 = new Browser();
        BrowserView browserView = new BrowserView(browser);

        JFrame frame = new JFrame();
        frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        frame.add(browserView, 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.swing.BrowserView;

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 = new Browser();
        BrowserView browserView = new BrowserView(browser);
        browser.loadURL(url);

        JInternalFrame internalFrame = new JInternalFrame(title, true);
        internalFrame.setContentPane(browserView);
        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.swing.BrowserView;

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 = new Browser();
        BrowserView browserView = new BrowserView(browser);

        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 + ")");
                }
            }
        });

        JButton setMarkerButton = new JButton("Set Marker");
        setMarkerButton.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                browser.executeJavaScript("var myLatlng = new google.maps.LatLng(48.4431727,23.0488126);\n" +
                        "var marker = new google.maps.Marker({\n" +
                        "    position: myLatlng,\n" +
                        "    map: map,\n" +
                        "    title: 'Hello World!'\n" +
                        "});");
            }
        });

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

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

        // Provide the correct full path to the map.html file, e.g. D:\\map.html
        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.SavePageType;
import com.teamdev.jxbrowser.chromium.events.FinishLoadingEvent;
import com.teamdev.jxbrowser.chromium.events.LoadAdapter;
import com.teamdev.jxbrowser.chromium.swing.BrowserView;

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 = new Browser();
        BrowserView browserView = new BrowserView(browser);

        JFrame frame = new JFrame();
        frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        frame.add(browserView, 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 java.io.File;

/**
 * By default all Browser instances with same BrowserContext share
 * cookies and cache data. This sample demonstrates how to create two 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 = new Browser(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 = new Browser(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.LoggerProvider;
import com.teamdev.jxbrowser.chromium.events.StatusEvent;
import com.teamdev.jxbrowser.chromium.events.StatusListener;
import com.teamdev.jxbrowser.chromium.swing.BrowserView;

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 = new Browser();
        BrowserView browserView = new BrowserView(browser);

        JFrame frame = new JFrame();
        frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        frame.add(browserView, 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.events.FinishLoadingEvent;
import com.teamdev.jxbrowser.chromium.events.LoadAdapter;
import com.teamdev.jxbrowser.chromium.swing.BrowserView;

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 = new Browser();
        BrowserView browserView = new BrowserView(browser);

        JFrame frame = new JFrame();
        frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        frame.add(browserView, 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 *.html file that uses local JQuery jquery.min.js file. Path
        // to the local jquery.min.js file must be relative.
        browser.loadURL("d:\\jquery.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;

/**
 * This sample demonstrates how to clear the Browser's cache. If you create
 * several browser instances by calling new Browser() or
 * new Browser(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 = new Browser(context1);
        Browser browser2 = new Browser(context1);

        BrowserContext context2 = new BrowserContext("C:\\my-data2");
        Browser browser3 = new Browser(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.swing.BrowserView;

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 = new Browser();
        BrowserView browserView = new BrowserView(browser);

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

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

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

Execute Command

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

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 = new Browser();
        BrowserView browserView = new BrowserView(browser);

        JFrame frame = new JFrame();
        frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        frame.add(browserView, 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) {
        System.out.println("JxBrowser version: " + ProductInfo.getVersion());
    }
}

Web Preferences

import com.teamdev.jxbrowser.chromium.Browser;
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) {
        BrowserPreferences.setChromiumSwitches("");

        Browser browserOne = new Browser();
        // 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 = new Browser();
        browserTwo.loadURL("http://www.teamdev.com/");
    }
}

Navigation History

import com.teamdev.jxbrowser.chromium.Browser;
import com.teamdev.jxbrowser.chromium.NavigationEntry;
import com.teamdev.jxbrowser.chromium.swing.BrowserView;

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 = new Browser();
        BrowserView browserView = new BrowserView(browser);

        JFrame frame = new JFrame();
        frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        frame.add(browserView, 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 com.teamdev.jxbrowser.chromium.swing.BrowserView;
import com.teamdev.jxbrowser.chromium.swing.DefaultNetworkDelegate;

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.getNetworkService().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 = new Browser(browserContext);
        BrowserView browserView = new BrowserView(browser);

        JFrame frame = new JFrame();
        frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        frame.add(browserView, 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.BrowserPreferences;
import com.teamdev.jxbrowser.chromium.swing.BrowserView;

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 = new Browser();
        BrowserView browserView1 = new BrowserView(browser1);

        // 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(browserView1, 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 = new Browser();
        BrowserView browserView2 = new BrowserView(browser2);

        JFrame frame2 = new JFrame();
        frame2.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        frame2.add(browserView2, 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;

Plugin Manager

import com.teamdev.jxbrowser.chromium.Browser;
import com.teamdev.jxbrowser.chromium.PluginFilter;
import com.teamdev.jxbrowser.chromium.PluginInfo;
import com.teamdev.jxbrowser.chromium.PluginManager;
import com.teamdev.jxbrowser.chromium.swing.BrowserView;

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

/**
 * This sample demonstrates how to work with plugin manager to get a list
 * of all available plugins and disable all plugins except PDF Viewer using
 * our own PluginFilter.
 */
public class PluginManagerSample {
    public static void main(String[] args) {
        Browser browser = new Browser();
        BrowserView browserView = new BrowserView(browser);

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

        PluginManager pluginManager = browser.getPluginManager();

        // Get information about all available plugins.
        List<PluginInfo> pluginsList = pluginManager.getPluginsInfo();
        for (PluginInfo plugin : pluginsList) {
            System.out.println("Plugin Name: " + plugin.getName());
            System.out.print("Plugin Mime-Types: ");
            for (String mimeType : plugin.getMimeTypes()) {
                System.out.print(mimeType + ';');
            }
            System.out.println("\n---------");
        }

        // Register plugin filter that disables all plugins except the one that
        // supports "application/pdf" mime type.
        pluginManager.setPluginFilter(new PluginFilter() {
            @Override
            public boolean isPluginAllowed(PluginInfo pluginInfo) {
                return pluginInfo.getMimeTypes().contains("application/pdf");
            }
        });
        browser.loadURL("http://www.education.gov.yk.ca/pdf/pdf-test.pdf");
    }
}

XPath

import com.teamdev.jxbrowser.chromium.Browser;
import com.teamdev.jxbrowser.chromium.XPathResult;
import com.teamdev.jxbrowser.chromium.dom.DOMDocument;
import com.teamdev.jxbrowser.chromium.events.FinishLoadingEvent;
import com.teamdev.jxbrowser.chromium.events.LoadAdapter;
import com.teamdev.jxbrowser.chromium.swing.BrowserView;

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

/**
 * This sample demonstrates how to evaluate the XPath expression and work with the result.
 */
public class XPathSample {
    public static void main(String[] args) {
        final Browser browser = new Browser();
        BrowserView browserView = new BrowserView(browser);

        JFrame frame = new JFrame();
        frame.getContentPane().add(browserView, 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 = browser.getDocument();
                    XPathResult result = document.evaluate("count(//div)");
                    // If the expression is not a valid XPath expression or the document
                    // element is not available, we'll get an error.
                    if (result.isError()) {
                        System.out.println("Error: " + result.getErrorMessage());
                        return;
                    }

                    // Make sure that result is a number.
                    if (result.isNumber()) {
                        System.out.println("Result: " + result.getNumber());
                    }
                }
            }
        });
        browser.loadURL("http://www.teamdev.com/jxbrowser");
    }
}

Get Selected Text

import com.teamdev.jxbrowser.chromium.Browser;
import com.teamdev.jxbrowser.chromium.swing.BrowserView;

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

/**
 * The sample demonstrates how to get selected text on a web page.
 */
public class GetSelectedTextSample {
    public static void main(String[] args) {
        final Browser browser = new Browser();
        final BrowserView browserView = new BrowserView(browser);

        JButton button = new JButton("Get Selected Text");
        button.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                String selectedText = browser.getSelectedText();
                JOptionPane.showMessageDialog(browserView,
                        selectedText, "Selected Text", JOptionPane.PLAIN_MESSAGE);
            }
        });

        JFrame frame = new JFrame();
        frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        frame.add(button, BorderLayout.NORTH);
        frame.add(browserView, BorderLayout.CENTER);
        frame.setSize(800, 600);
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);

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

Printing

import com.teamdev.jxbrowser.chromium.Browser;
import com.teamdev.jxbrowser.chromium.PrintJob;
import com.teamdev.jxbrowser.chromium.PrintSettings;
import com.teamdev.jxbrowser.chromium.PrintStatus;
import com.teamdev.jxbrowser.chromium.events.PrintJobEvent;
import com.teamdev.jxbrowser.chromium.events.PrintJobListener;
import com.teamdev.jxbrowser.chromium.swing.BrowserView;
import com.teamdev.jxbrowser.chromium.swing.DefaultPrintHandler;

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

/**
 * The sample demonstrates how to print currently loaded web page with custom print settings.
 */
public class PrintSample {
    public static void main(String[] args) {
        final Browser browser = new Browser();
        BrowserView browserView = new BrowserView(browser);

        JFrame frame = new JFrame();
        frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        JButton print = new JButton("Print");
        print.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                browser.print();
            }
        });
        frame.add(print, BorderLayout.NORTH);
        frame.add(browserView, BorderLayout.CENTER);
        frame.setSize(700, 500);
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);

        browser.setPrintHandler(new DefaultPrintHandler() {
            @Override
            public PrintStatus onPrint(PrintJob printJob) {
                PrintSettings printSettings = printJob.getPrintSettings();
                printSettings.setLandscape(true);
                printSettings.setPrintBackgrounds(true);
                printJob.addPrintJobListener(new PrintJobListener() {
                    @Override
                    public void onPrintingDone(PrintJobEvent event) {
                        System.out.println("PrintingDone success: " + event.isSuccess());
                    }
                });
                return PrintStatus.CONTINUE;
            }
        });

        browser.loadURL("http://www.javascriptkit.com/howto/newtech2.shtml");
    }
}

Disable Backspace

import com.teamdev.jxbrowser.chromium.Browser;
import com.teamdev.jxbrowser.chromium.DefaultLoadHandler;
import com.teamdev.jxbrowser.chromium.swing.BrowserView;

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

/**
 * The sample demonstrates how to handle navigation on Backspace and
 * Shift+Backspace.
 */
public class DisableBackspaceNavigationSample {
    public static void main(String[] args) {
        Browser browser = new Browser();
        BrowserView browserView = new BrowserView(browser);
        browser.setLoadHandler(new DefaultLoadHandler() {
            @Override
            public boolean canNavigateOnBackspace() {
                return false;
            }
        });

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

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

Cookie Filter

import com.teamdev.jxbrowser.chromium.Browser;
import com.teamdev.jxbrowser.chromium.Cookie;
import com.teamdev.jxbrowser.chromium.swing.BrowserView;
import com.teamdev.jxbrowser.chromium.swing.DefaultNetworkDelegate;

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

/**
 * The sample demonstrates how to filter incoming and outgoing cookies.
 */
public class CookieFilterSample {
    public static void main(String[] args) {
        Browser browser = new Browser();
        BrowserView browserView = new BrowserView(browser);

        // Disable all incoming and outgoing cookies.
        browser.getContext().getNetworkService().setNetworkDelegate(new DefaultNetworkDelegate() {
            @Override
            public boolean onCanSetCookies(String url, List<Cookie> cookies) {
                return false;
            }

            @Override
            public boolean onCanGetCookies(String url, List<Cookie> cookies) {
                return false;
            }
        });

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

Access Local Files

import com.teamdev.jxbrowser.chromium.Browser;
import com.teamdev.jxbrowser.chromium.BrowserPreferences;
import com.teamdev.jxbrowser.chromium.swing.BrowserView;

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

/**
 * The sample demonstrates how to enable access to local files from a web page.
 */
public class LoadLocalFilesSample {
    public static void main(String[] args) {
        BrowserPreferences.setChromiumSwitches("--disable-web-security", "--allow-file-access-from-files");

        Browser browser = new Browser();
        BrowserView browserView = new BrowserView(browser);

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

        browser.loadHTML("<html><body>Image:<img src='file:///C:\\image.jpg'></body></html>");
    }
}