Java调用JS

先是使用JS调用了Java,成功了:

      loadTopOnRewardVideoAD(caller: any, id: string, callback: (isFinished: boolean) => void) {

            window["RewardVideoPlayComplete"]=function(){
                console.log("Kola_TC callback");
                callback.call(caller, true);
            }

            console.log("Kola_TC RewardVideoPlayComplete ");

            if (cc.sys.platform == cc.sys.ANDROID) {
                console.log("Kola_TC loadTopOnRewardVideoAD" + this.ANDROID_LOCATION);

                switch (id) {
                    case this.CLICK_AD_1:
                        jsb.reflection.callStaticMethod(this.ANDROID_LOCATION, "toLoadInterstitialAD", "()V");
                        break; 
               }
          }
}

然后在Java里回调Cocos失败:

private static void getRewardToCocos() {
        Log.d(TAG, "getRewardToCocos: ");
        Cocos2dxHelper.runOnGLThread(new Runnable() {
            @Override
            public void run() {
                Cocos2dxJavascriptJavaBridge.evalString("RewardVideoPlayComplete()");
            }
        });
    }

堆栈日志:
2025-07-09 22:16:56.763 4723-4723 AppAdmobManager com.xtimestudio.blackball D getRewardToCocos:
2025-07-09 22:16:56.763 4723-4751 jswrapper com.xtimestudio.blackball E ScriptEngine::evalString catch exception:
2025-07-09 22:16:56.763 4723-4751 jswrapper com.xtimestudio.blackball E ERROR: Uncaught ReferenceError: RewardVideoPlayComplete is not defined, location: (no filename):0:0
STACK:
[0]anonymous@(no filename):1
2025-07-09 22:16:56.764 4723-4751 debug info com.xtimestudio.blackball D Uncaught Exception:
- location : (see stack)
- msg : Uncaught ReferenceError: RewardVideoPlayComplete is not defined
- detail :
[0]anonymous@(no filename):1
2025-07-09 22:16:56.764 4723-4751 jswrapper com.xtimestudio.blackball D JS: [ERROR]: (see stack) Uncaught ReferenceError: RewardVideoPlayComplete is not defined [0]anonymous@(no filename):1
2025-07-09 22:16:56.765 4723-4751 jswrapper com.xtimestudio.blackball E ScriptEngine::evalString script (no filename), failed!

看上去是Cocos的RewardVideoPlayComplete方法定义有问题。正确的2X的版本需要怎么写呢?
链接:基于反射机制实现 JavaScript 与 Android 系统原生通信 | Cocos Creator 这个是3D的写法吧

mark。。

没看出问题,不过可以猜一下,没找到函数,是不是这个脚本没有被加载?

RewardVideoPlayComplete is not defined
你怎么定义的这个函数,贴出来看下
要定义成全局的
比如window.RewardVideoPlayComplete = finction(){
}
java调用时就写
Cocos2dxJavascriptJavaBridge.evalString(“window.RewardVideoPlayComplete()”);


window[“RewardVideoPlayComplete”]=function(){
console.log(“Kola_TC callback”);
callback.call(caller, true);
}

是定义在同一个js脚本里的啊。按理说肯定是都加载了吧

是定义在loadTopOnRewardVideoAD这个方法里的

修改了Cocos代码后,记得在Android项目中clean然后重新build一下。

有啥意义呢