JavaScript in the SWT Browser widget

At the Eclipse Summit Europe I listened to a talk of Boris Bokowski about Eclipse and the Web.

Among other things I learned that you can execute JavaScript directly on the SWT Browser Widget and I wanted to give a tiny example for this.

This Eclipse view will for example load my webpage and then execute a tiny JavaScript (alert(“1″);) in the browser.

[sourcecode language=”java”]

package de.vogella.swtbrowser;

import org.eclipse.swt.SWT;
import org.eclipse.swt.browser.Browser;
import org.eclipse.swt.browser.ProgressEvent;
import org.eclipse.swt.browser.ProgressListener;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.ui.part.ViewPart;

public class View extends ViewPart {

public static final String ID = "de.vogella.swtbrowser.view";

public void createPartControl(Composite parent) {
final Browser b = new Browser(parent, SWT.NONE);
b.setUrl("www.vogella.de");
b.addProgressListener(new ProgressListener() {
@Override
public void completed(ProgressEvent event) {
System.out.println("Page loaded");
System.out.println(b.execute("alert(\"1\");"));
}
@Override
public void changed(ProgressEvent event) {
}
});
}

/**
* Passing the focus request to the viewer’s control.
*/
public void setFocus() {
}
}

[/sourcecode]

Thanks to Boris for the great talk.

About Lars Vogel

Lars Vogel is the founder and CEO of the vogella GmbH and works as Eclipse and Android consultant, trainer and book author. He is a regular speaker at international conferences, He is the primary author of vogella.com. With more than one million visitors per month this website is one of the central sources for Java, Eclipse and Android programming information.
This entry was posted in Eclipse and tagged , . Bookmark the permalink.

4 Responses to JavaScript in the SWT Browser widget

Comments are closed.