In GWT, adding an event handler to any of the homepage tags

I want to add a MouseOver event handler for any tag. Say, for example, that I want to add an event handler for each bind page on an outdated HTML page.

Following the GWT guide , I was able to use their JSNI method, proposed to retrieve all anchor tags after fixing small errors (missing brackets and types).

However, I want to use the elements collected in the ArrayList and bind them all to an event handler. How can i do this?

The code I wrote is below:

  private native void putElementLinkIDsInList(BodyElement elt, ArrayList list) /*-{
    var links = elt.getElementsByTagName("a");

    for (var i = 0; i < links.length; i++ ) {
      var link = links.item(i);
      link.id = ("uid-a-" + i);
      list.@java.util.ArrayList::add(Ljava/lang/Object;) (link.id);
    }
  }-*/;

  /**
   * Find all anchor tags and if any point outside the site, redirect them to a
   * "blocked" page.
   */
  private void rewriteLinksIterative() {
    ArrayList links = new ArrayList();
    putElementLinkIDsInList(Document.get().getBody(), links);
    for (int i = 0; i < links.size(); i++) {
      Element elt = DOM.getElementById((String) links.get(i));
      rewriteLink(elt, "www.example.com");
    }
  }

 /**
   * Block all accesses out of the website that don't match 'sitename'
   * 
   * @param element
   *          An anchor link element
   * @param sitename
   *          name of the website to check. e.g. "www.example.com"
   */
  private void rewriteLink(Element element, String sitename) {
    String href = DOM.getElementProperty(element, "href");

    if (null == href) {
      return;
    }

    // We want to re-write absolute URLs that go outside of this site
    if (href.startsWith("http://")
        && !href.startsWith("http://" + sitename + "/")) {
      DOM.setElementProperty(element, "href", "http://" + sitename
          + "/Blocked.html");
    }
  }
+2
source share
1 answer

, , Document.getElementsByTagName("a"), NodeList, , AnchorElement href.

:

NodeList<Element> elems = Document.get().getElementsByTagName("a");
for (int i = 0; i < elems.getLength(); i++) {
  Element elem = elems.getItem(i);
  AnchorElement a = AnchorElement.as(elem);
  if (!a.getHref().startsWith("http://yoursite.com")) {
    a.setHref("http://yoursite.com/blockedpage");
  }
}

, Element Anchor wrap()

for (int i = 0; i < elems.getLength(); i++) {
  Element elem = elems.get(i);
  Anchor a = Anchor.wrap(elem);
  a.addClickHandler(new ClickHandler() {
    @Override
    public void onClick(ClickEvent event) {
      Window.alert("yay!");
    }
  });
}

( , ClickHandler )

+2

All Articles