通过 GWT 中的框架从 javascript 调用 JSNI Java 函数 - $wnd 未定义错误

Call JSNI Java function from javascript via a frame in GWT - $wnd is undefined error

我知道我可能只是在做一些愚蠢的事情,但我找不到实际展示如何使用 GWT 从 javascript 调用 Java 方法的示例。

I've followed the documentation almost verbatim where is says:

package mypackage;

public class Account {
private int balance = 0;
public int add(int amt) {
  balance += amt;
}

public native void exportAdd() /*-{
    var that = this;
    $wnd.add = $entry(function(amt) {
      that.@mypackage.Account::add(I)(amt);
    });
}-*/;
}

然后你可以在JS中使用

调用它
$wnd.add(5);

但这对我来说是一个错误,提示“$wnd is undefined”。

这是我的代码: 我导出函数调用

public native void exportPaymentProcessComplete()/*-{
    var that = this;
    console.log('exportingPaymentProcessComplete');
    $wnd.paymentProcessComplete = $entry(function(result){
        that.@com.ec.client.checkout.Presenter::paymentProcessComplete(Ljava/lang/String;)(result);
    });

}-*/;

我有一个正在调用的简单函数(有一个断点,因为我还没有调用它)

public void paymentProcessComplete(String result){
    if(result != null){

    }
}

这是棘手的部分,可能是我出错的地方。 JSNI 调用是在加载时从 iframe 进行的。我认为这与尝试调用父 window 的 javascript 函数有关,但我不确定如何引用父 $wnd 对象。

我试过这个:

response.getWriter().print("<script type=\"text/javascript\">parent.$wnd.paymentProcessComplete(\"SUCCESS\");</script>");

这是我收到“$wnd is undefined”错误的时候。

还有这个:

response.getWriter().print("<script type=\"text/javascript\">parent.paymentProcessComplete(\"SUCCESS\");</script>");

这给了我 "Unable to get property 'paymentProcessComplete' of undefined or null reference"。这基本上与“$wnd is undefined”的错误相同。

有人对如何实现这个有任何想法吗?

编译您的 GWT 应用程序时 $wndwindow 替换。 因此,当您尝试从 iframe 中调用导出的方法时,请像这样调用它:
window.parent.paymentProcessComplete("SUCCESS")

经过更深入的挖掘,我发现 exporting/exposing 我的 JAVA 方法的 JSNI 代码抛出了一个 Cast 异常,因为它试图将它附加到 Presenter class它是 Window.

的一部分

所以这段代码:

public native void exportPaymentProcessComplete()/*-{
    var that = this;
    console.log('exportingPaymentProcessComplete');
    $wnd.paymentProcessComplete = $entry(function(result){
        that.@com.ec.client.checkout.Presenter::paymentProcessComplete(Ljava/lang/String;)(result);
    });
}-*/;

变成了这个代码:

public native void exportPaymentProcessComplete()/*-{
    $wnd.paymentProcessComplete = $entry(function(result){
        @com.ra.ec.client.checkout.CheckoutPresenter::paymentProcessComplete(Ljava/lang/String;)(result);
    });     
}-*/;

这也意味着 paymentProcessComplete() 方法必须对其声明应用静态修饰符。

private static void paymentProcessComplete(String result){