Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Hooking a GWT event onto an element in an external iframe

I am writing a GWT app that involves interacting with an external document in an iframe. As a proof of concept, I am trying to attach a click handler to a button.

The following works in javascript

var iframe = document.getElementById("rawJSIFrame");
var doc = iframe.contentDocument;
var body = doc.body;
var button = doc.getElementsByTagName("input").namedItem("submit");
button.onclick = function() {
    alert("Clicked!");
};

Trying to do the equivalent in GWT, I did the following:

public void addClickHandlerToSubmitButton(String buttonElementName, ClickHandler clickHandler) {
    IFrameElement iframe = IFrameElement.as(frame.getElement());
    Document frameDocument = getIFrameDocument(iframe);
    if (frameDocument != null) {
        Element buttonElement = finder(frameDocument).tag("input").name(buttonElementName).findOne();
        ElementWrapper wrapper = new ElementWrapper(buttonElement);
        HandlerRegistration handlerRegistration = wrapper.addClickHandler(clickHandler);
    }
}

private native Document getIFrameDocument(IFrameElement iframe)/*-{
        return iframe.contentDocument;
}-*/;

The following is the ElementWrapper class:

public class ElementWrapper extends Widget implements HasClickHandlers {

    public ElementWrapper(Element theElement) {
        setElement(theElement);
    }

    public HandlerRegistration addClickHandler(ClickHandler handler) {
        return addDomHandler(handler, ClickEvent.getType());
    }


}

The code to find the button works fine but the actual click event handler is not getting invoked. Has anybody had a similar issue before, and how did you resolve it?

Thanks in advance,

Tin

like image 223
triggerNZ Avatar asked Jul 16 '09 23:07

triggerNZ


2 Answers

Hilbrand is right about the problem being that the GWT method onAttach() was not called.

I implemented your original solution, adding the following method to ElementWrapper:

  public void onAttach() {
    super.onAttach();
  }

And called added wrapper.onAttach() after the ElementWrapper is created. Works like a charm!

like image 51
Tina Avatar answered Oct 08 '22 04:10

Tina


I expect the problem is that the GWT method onAttach() is not called when you use the wrapping as in your first example. You can try to use the static wrap method on the Button widget. Although to use this the input must be of type button. Or have a look at the implementation of the wrap method. Here is the modified code when using the wrap method:

Element buttonElement = finder(frameDocument).tag("input").name(buttonElementName).findOne();
Button button = Button.wrap(buttonElement);
HandlerRegistration handlerRegistration = button.addClickHandler(clickHandler);
like image 45
Hilbrand Bouwkamp Avatar answered Oct 08 '22 04:10

Hilbrand Bouwkamp