Saturday, December 19, 2009

Adsense Ads and GWT - Making it work.

It seems like a lot of people have had this same problem, but I haven't found anywhere on the net where someone has found a solution. Here's how I got it to work. If you find this post helpful, I would ask the favor that you check out, and ask your friends to do the same.

I struggled for a long time trying to get an Adsense ad to appear in a <div>, but that seems to be the wrong approach. Divs are nice for styling reasons, but it seems that Adsense knows when it's in a div, and won't display.

I avoided IFrames (which is what the GWT Frame object compiles to) because sizing isn't automatic. Eventually, though, it became apparent that IFrames were the way to go, since Adsense ads will load in them. I create an IFrame and point it at a static page that contains the necessary Adsense script. That just works. The content loads correctly, and ads will display.

But here's the rub. IFrames need to be sized with custom javascript. I use this javascript: This works easily for all browsers except - you guessed it - IE. Below is the GWT code that I use to bring it all together, including a work-around for IE.

public static native String getUserAgent() /*-{
return navigator.userAgent.toLowerCase();

private Widget buildMainPanel() {
Widget mainPanel;
if(getUserAgent().contains("msie")) {
mainPanel = buildIEPanel();
} else {
mainPanel = buildNonIEPanel();


return mainPanel;

private Widget buildNonIEPanel() {
Frame mainPanel = new Frame();
mainPanel.getElement().setAttribute("onLoad", "resizeCaller();");

return mainPanel;

private Panel buildIEPanel() {
Panel mainPanel = new VerticalPanel();

HTML adBar = new HTML("Loading...");

try {
RequestBuilder builder = new RequestBuilder(RequestBuilder.GET, GWT.getModuleBaseURL() + "ie_ads/index.html");
builder.sendRequest(null, new RequestHandler(adBar, null));
} catch (RequestException e) {

HTML content = new HTML("Loading...");

String errorMessage = "Failed to load content, please try again later.";
try {
RequestBuilder builder = new RequestBuilder(RequestBuilder.GET, GWT.getModuleBaseURL() + getRootPage());
builder.sendRequest(null, new RequestHandler(content, errorMessage));
} catch (RequestException e) {

return mainPanel;