简体   繁体   中英

How to call a JavaScript callback from a Java applet thread?

I have some long-running Java code running in a thread started by a Java applet. As soon as the code has finished, it has information for the user. I'd like to pass this information to a JavaScript callback in a thread-safe way. Just using the Java DOM API to modify the HTML document is not good enough, unless my JavaScript callback gets called as a side effect in a thread safe way (ie eventually, in the same browser thread where JavaScript callbacks execute). How can I implement this? Are there libraries already doing it?

Looks as though the Common DOM API is what you need. In essence you request a DOMService to call you back on the main UI thread when it is good and ready.

http://docs.oracle.com/javase/1.5.0/docs/guide/plugin/developer_guide/java_js.html

As I understand things, JSObject is the "old way" and the Common DOM API is the newer way (as of Java 6). What you need to do is call a method of your applet and pass the function object that you want to have called back. Your applet then calls that function object from within your DOMAction.

I have no code at hand to show you and this is not something I've done before using Java. However I have used a similar technique from with an NPAPI web plugin written in C++ ie had JS call my C++ object passing a function as a parameter, and then at a later stage, have the C++ object call the JS function. 'hope that this helps.

I had concurrency issues with multiple applet threads calling Javascript. Some of the calls were simply ignored by Internet Explorer 8 (Firefox 3.6 and Safari 5 worked fine).

I tried to wrap calls to Javascript with DOMService.invokeAndWait - that didn't help.

I ended up ensuring that all the Java->Javascript calls are made from the same thread, and my problems were solved (at least temporarily - I haven't checked what happens if the Javascript thread is busy with some user-initiated work).

To serialize the calls, I used Executors.newSingleThreadExecutor

It seems that there is no public tutorial how to do it. The whole JavaScript--Java interface is underdocumented, and it is subject to browser limitations.

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