Examples‎ > ‎

JavaScript Execution

This sample shows how to access and change javascript variables:
import com.jniwrapper.win32.ie.Browser;
 
import javax.swing.*;
import java.awt.*;
 
/**
 * This sample shows how to access and change javascript variables.
 */
public class JavascriptSample {
    private static final String HTML_CONTENT =
            "<html><head>" +
                    "<script>var counter = 1;</script>" +
                    "</head><body>" +
                    "<div id='theDiv'>initial text</div>" +
                    "</body></html>";
 
    public static void main(String[] args) throws Exception {
        Browser browser = new Browser();
 
        JFrame frame = new JFrame("JExplorer");
        frame.setSize(700, 500);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setLocationRelativeTo(null);
        frame.getContentPane().add(browser, BorderLayout.CENTER);
        frame.setVisible(true);
 
        browser.setContent(HTML_CONTENT);
        browser.waitReady();
 
        // Executes JavaScript
        String counter = (String) browser.executeScript("counter");
        System.out.println("counter variable = " + counter);
 
        // Set JavaScript counter variable
        browser.executeScript("counter = 7;");
 
        counter = (String) browser.executeScript("counter");
        System.out.println("counter variable = " + counter);
    }
}