简体   繁体   中英

GWT Javascript Injection and JSNI

How can I use a Javascript library (downloaded from a CDN) inside JSNI code?

For example, I would like to call the javascript Stripe method, from within this JSNI method:

    private native void contactStripe(String creditCard, String cvc, String expiryMonth, String expiryYear) /*-{
        $wnd.Stripe.setPublishableKey('my_stripe_publishable_key');
        $wnd.Stripe.createToken({
            number: creditCard,
            cvc: cvc,
            exp_month: expiryMonth,
            exp_year: expiryYear
        }, callBack);
    }-*/;

... but the Stripe javascript method is undefined.

(more on the Stripe.createToken method https://stripe.com/docs/tutorials/forms#create-a-single-use-token )

The Stripe javascript file is injected using the CDN url:

ScriptInjector.fromUrl("https://js.stripe.com/v1/").setCallback(
    new Callback<Void, Exception>() {
    public void onFailure(Exception reason) {
    }
    public void onSuccess(Void result) {
        contactStripe("0000111122223333", "456", "04", "2014");
    }
}).inject();

如果您希望以一种可以通过$wnd setWindow访问它定义的全局变量的方式注入JS脚本,则必须设置setWindow ( ScriptInjector.TOP_WINDOW )

Try to change your code to:

private native void contactStripe(String creditCard, String cvc, String expiryMonth, String expiryYear) /*-{

    console.log($wnd.Stripe);             // Should log 'Object'
    console.log($wnd.Stripe.createToken); // should log function
    var obj = {
        number: creditCard,
        cvc: cvc,
        exp_month: expiryMonth,
        exp_year: expiryYear
    };
    consloe.log(obj);                     // Should be 'Object'
    $wnd.Stripe.createToken(obj, callBack);
}-*/; 

If you use the chrome debugging tools, you can inspect all these objects .

update You don't provide the callback. Is that your problem?

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