Accessing an iframe's JavaScript function via GWT
Posted by Manolis Platakis on 18-07-2010 at 20:13
During the past 2 years I've been coding a lot with Google Web Toolkit (GWT), watching it as it evolves into a powerful rapid web development framework enabling traditional system/software developers (like myself) to code Java and get JavaScript code cross-browser compatible. This is what GWT is all about; you code your web application in Java and you compile to fully functioning JavaScript code. Its architecture provides the developer with a very easy way to integrate the client side application with server side RPC calls. Along with the several widgets that come with GWT and a bunch of existing GWT libraries, like Smart GWT, GWT can become a powerful tool in one's hand. But powerful as it may be, there are times that you need to write native JavaScript in order to achieve what you want. GWT offers an easy way to mix Java and JavaScript, called JSNI. Recently, I had to call a function of a separate iframe that I had embedded in my GWT application. Coming up next, how it's done, in case anyone needs it.

First of all make sure you use a GWT NamedFrame like this:
NamedFrame myFrame = new NamedFrame("exampleFrame");
DOM.setElementAttribute(myFrame.getElement(), "id",
myFrame.getName());
myFrame.nativeFunct();
Next, this is how you code your JavaScript native function to call your iframe's function.
public native void nativeFunct() /*-{
var f = $wnd.frames["exampleFrame"];
f.contentWindow.myFunction();
}-*/;
Notice how in GWT you have to use $wnd to access the window element (and $doc to access the document element). The final step is to make sure that the JavaScript function myFunction is publicly visible to the window object in our frame's HTML/JS code.
var myFunction = new function() 
{
/* swap the alert with your actual logic */
alert("It's working!");
return;
}
Of course both your JSNI and JavaScript functions can also accept arguments. Last but not least, it's always best if both the iframe and the GWT application operate in the same web server.
Sources: 1, 2
Kudos: To this website for helping me out with the formatting of my source code.
Comment on This Post

Image password:
The Captcha image
Phonetic spelling (mp3)