I have an applet and an iframe within the same page. The iframe tag has an onload attribute which calls a method in the applet every time the iframe page is changed. The applet needs to access the elements of the iframe document and count the number of different types of tag on the page.
I have the following code in the applet, which accesses the iframe
Class c = Class.forName("com.sun.java.browser.plugin2.DOM");
Method m = c.getMethod("getDocument", new Class[]{java.applet.Applet.class});
Object obj = m.invoke(null, new Object[]{this});
HTMLDocument doc = (HTMLDocument)obj;
NodeList nodeList = document.getElementsByName("iframe");
if (nodeList.getLength()>0) {
Node node1 = nodeList.item(0);
if (node1 instanceof HTMLIFrameElement) {
Document doc = ((HTMLIFrameElement)node1).getContentDocument();
if (doc instanceof HTMLDocument) {
document = (HTMLDocument)doc;
if (document.hasChildNodes() {
// do some stuff
}
}
}
}
}
If this script is run when the page first loads, it works fine - it accesses the code of the iframe and can access each element within the page.
But when the applet code is invoked from the onload attribute of the iframe, the applet can't read the document properly. It throws the following exception:
netscape.javascript.JSException: No such property "hasChildNodes" on JavaScript object
I'm accessing exactly the same document both times, so why does it fail when I use onload? Is there any way I can get around this?