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.


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() {
	}
}

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

  1. Jeff McAffer says:

    For more examples of this, see the Toast example at http://wiki.eclipse.org/Toast. (see org.eclipse.examples.toast.dev.google) There we use browser widget to do Google Earth integration. There is a bit of JS code that did not make it through the CQ process. I’ll be rewriting that in the near future and will commit it directly. Note that you can also look Toast RAP related bundles for integrating Google stuff in RAP using their version of the SWT Browser widget.

  2. David Song says:

    hi Vogel, thanks for your so goog tutorials. I think if you record screen videos, that’s even better!

    Thanks

  3. Lars Vogel says:

    @David: I doubled that videos are good for learning how to write code.

  4. David Song says:

    Yes, why not cooperate with lynda.com ?

Comments are closed.