This example demonstrates how to use JavaScript MutationObserver in combination with JavaScript Java Bridge API. The goal of this example is to transmit every change of the HTML element to the Java side and display it in the Output window.


The HTML page that we are listening to has a timer that updates the value of the span element. The source code of the page is the following:

<!DOCTYPE html>
<html>
  <head>
    <title>index</title>
  </head>
  <body>
    <div>
      <span class="countdown" id="countdown"></span>
    </div>
    <script src="https://code.jquery.com/jquery-3.2.1.slim.min.js"
               crossorigin="anonymous"></script>
    <script type="text/javascript">
        $(document).ready(function () {
          var counter = 1;
          setInterval(function() { $(".countdown").text(counter++); }, 1000);
        });
    </script>
  </body>
</html>


The source code of the Swing application that displays the web page, injects MutationObserver and listens to it is the following:

public class DOMContentChangeListenerSample {
    public static void main(String[] args) {
        final Browser browser = new Browser();
        BrowserView view = new BrowserView(browser);

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

        browser.addLoadListener(new LoadAdapter() {
            @Override
            public void onDocumentLoadedInMainFrame(LoadEvent event) {
                Browser browser = event.getBrowser();
                JSObject window = browser.executeJavaScriptAndReturnValue("window").asObject();
                window.setProperty("java", new DOMContentChangeListenerSample.JavaObject());

                String javaScript = "function createObserver(){var element=document.body;var observer=new MutationObserver(" +
                        "function(mutations){mutations.forEach(function(mutation){for(var node of mutation.addedNodes)" +
                        "{if(node.className=='class_name'){window.java.onDomChanged()}}})});" +
                        "var config={childList:!0};observer.observe(element,config)}createObserver();";
                browser.executeJavaScript(javaScript);
            }
        });

        String path = new File(".").getAbsolutePath();

        browser.loadURL(path + "index.html");
    }

    private static class JavaObject {
        void onDomChanged() {
            System.out.println("DOM node changed");
        }
    }
}