简体   繁体   中英

java applet: How to invoke/access javascript variable of web page from applet?

An example:

getAppletContext().showDocument(
  new URL("javascript:alert(document.getElementById('textbox').value);"
));

Instead of alerting this textbox value, I want to use this value further as string variable in my applet program. How can i achieve this?

Multiple ideas for different approaches. Here are some:


Put the input-field in the Applet. Instead of adding an <input> -tag to the HTML-page, you can get input in the Applet by adding AWT components (or, when using a JApplet you can use the newer Swing toolkit) to it. Although Swing should be preferred.

Of course, if you can't change the applet-code, this is not an option.


Use the <param> -tag. You can give your applet some initial values (eg parameters), by using the <param> -tag in the <applet> -tag as shown by this example from the tag-doc :

<applet code="A21" width="256" height="256" archive="toir.jar">
  <param name="img" value="test.gif">
</applet>

However, as I said, these are initial values. If you change them while the applet is already running, they won't change in the Applet itself.

So, if the values in your <input> -tag are for initial values, you can use this (and manipulate the value -attribute with JS). If you want to change the values while the applet is running, this only works if you restart the applet (which might not be the best idea).


Use "Java-to-Javascript Communication". There is a certain document introducing the JSObject -class. It can be found here . There is also the "Common DOM API" which can be used to access the DOM-structure of the HTML-page. It sounds like what you're searching for, but it seems a little outdated.

Als, this seems to be no standard (just like the <applet> -tag) and therefor, some browsers might not or not completely implement support for that. You'll have to try it out.

// provide a JS function to return the value of textbox
// call it to get the value..
String userInput = JOptionPane.showInputDialog(this, value, ..

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM