How do I call a method of a Java instance from JavaScript?

前端 未结 3 1961
眼角桃花
眼角桃花 2020-12-09 20:26

I\'m using the Mozilla Rhino JavaScript emulator. It allows me to add Java methods to a context and then call them as if they were JavaScript functions. But I can\'t get it

3条回答
  •  旧时难觅i
    2020-12-09 20:48

    @Jawad's answer is great, but it still requires the parentScope to be a parent of the object you're trying to insert. If you want to add global functions into the scope created with initStandardObjects(), you have to use shared scope (which is sort of explained in the docs but lacks a full example).

    Here's how I did it (this is Android so please excuse the Kotlin):

    
    /**
     * Holds the global or "window" objects that mock browser functionality.
     */
    internal class Global() {
    
      fun requestAnimationFrame(callback: BaseFunction) {
        ...
      }
    
      fun setTimeout(callback: BaseFunction, delay: Int): Int {
        ...
      }
    
      fun clearTimeout(id: Int) {
        ...
      }
    
      internal fun register(context: Context, scope: Scriptable): Scriptable {
        return context.wrapFactory.wrapAsJavaObject(context, scope, this, Global::class.java)
      }
    }
    
    /**
     * Creates the root scope containing the StandardObjects, and adds Global functions to it.
     */
    fun createRootScope(): Scriptable {
      val context = Context.enter()
      val sharedScope = context.initSafeStandardObjects(null, true)
    
      val rootScope = Global().register(context, sharedScope)
      rootScope.prototype = sharedScope;
      rootScope.parentScope = null;
    
      return rootScope
    }
    

提交回复
热议问题