How can I retrieve elements from an HTML file that I attached to a GWT frame using setUrl()?

StackOverflow https://stackoverflow.com/questions/23488104

  •  16-07-2023
  •  | 
  •  

Question

I am using com.google.gwt.user.client.ui.Frame & displayed in an HTML file using frame.setUrl(FILEPATH).

I tried this code but it don't work:

frame.getElement().getElementsByTagName("table").getLength()

I want to fetch the width of a particular element in the HTML file and set the frame's width same to it.

I am using Eclipse with GWT Plugin.

EDIT: I got did it using these:

IFrameElement iframe = IFrameElement.as(frame.getElement());
Document frameDocument = iframe.getContentDocument();
String width= frameDocument.getElementsByTagName("table").getItem(0).getOffsetWidth() + "px";
frame.setWidth(tmpWidth);
Was it helpful?

Solution

First, as @apanizo said, you'll want to use a LoadHandler to make sure the document is loaded in the frame.

Then, to read into the frame's document, you'll have to use IFrameElement.as(frame.getElement()) or frame.getElement().<IFrameElement>cast() and then use getContentDocument().

IFrameElement.as(frame.getElement()).getContentDocument().getElementsByTagName("table").getLength()

A final note: this won't work if the document loaded in the frame is not from the same origin as your GWT app.

OTHER TIPS

Look waht NodeList#getLength() states:

The number of nodes in the list. The range of valid child node indices is 0 to length-1 inclusive.

you can try with Element#getOffsetWidth() or Element#getStyle() then Style#getWidth().

Sample code:

NodeList<Element> nodeList = frame.getElement().getElementsByTagName("table");

for (int i = 0; i < nodeList.getLength(); i++) {
    Element element = nodeList.getItem(i);
    System.out.println(element);
    System.out.println(element.getOffsetWidth());
    System.out.println(element.getStyle().getWidth());
}

Another approach. maybe is interesting for you to include a LoadHandler in order to wait until the iframe's content has been loaded (otherwise the DOM search could be empty) . Then, you can search inside the frame for the table element using GQuery selectors (like jQUery) and finally you set width.

Here is the code:

    final Frame yourFrame = new Frame("http://www.example.your.url.com");
    yourFrame.addLoadHandler(new LoadHandler() {

      @Override
      public void onLoad(LoadEvent event) {
        int elemWidth = GQuery.$(yourFrame).contents().find("table").width();
        yourFrame.setWidth(elemWidth+"px");

      }
    });

UPDATE: With @Manolo's comment!

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top