2

I am using rhino-android library to invoke java script code in java but I am not getting how to handle callback in javascript in java.

Java script code

   function TestingFunction(data, callback ){
        callback(data);
    }

I am trying to invoke the same in java- Android code

invocable.invokeFunction("TestingFunction","12345", ?(How to handle callback))

Can anyone suggest how to handle callback from javascript in java code ?

Naresh
  • 31
  • 6

1 Answers1

0

Passing a Java callback to a JavaScript function in Rhino should be possible by implementing the org.mozilla.javascript.Function interface, something like this:

invocable.invokeFuntion("TestingFunction", "12345", 
      new org.mozilla.javascript.Function() {

    @Override
    public Object call(Context cx, Scriptable scope, Scriptable thisObj,
          Object[] args) {

        String data = (String) args[0];
        // do stuff...
    });
Forketyfork
  • 7,416
  • 1
  • 26
  • 33
  • Hi Sergei, thanks for your response and it works fine. But my only concern is there are many overridden methods that gets generated in Function() callback is there any alternative to overcome this – Naresh Jul 28 '20 at 03:28
  • @Naresh I think you should be able to use org.mozilla.javascript.Callable instead, this is a super-interface of Function that only has a single call method. – Forketyfork Jul 28 '20 at 07:07
  • Hi Sergei, thanks for your support, Is there any way that I can invoke xmlhttprequest in js file from Android Java – Naresh Aug 03 '20 at 07:59
  • @Naresh I think this is a different question not directly related to the original one, so you could ask it as a separate question here. Maybe it's already answered, e.g. see https://stackoverflow.com/questions/13985560/xmlhttprequest-in-rhino – Forketyfork Aug 03 '20 at 08:02