Search code examples
javascriptgwtpaypaluibinderjavascript-injection

Add a javascript to uiBinder class in GWT, in order to use PaypalExpressCheckout in-context


I'm facing the problem to add a javascript in an uibinder XML. I have used in the uibinder.java the ScriptInjector, but it doesn't work because on Chrome console I receive the error:

IC_SETUP_CONTAINER_ERROR: Can't find element paypal

You can just ignore the href, my purpose is that would appear the link in a popup window. This is possible thanks to the 2 Javascript below offered by Paypal.

These are the important lines of code:

openPopupExpressCheckoutPayPal.js:

window.paypalCheckoutReady=function(){
paypal.checkout.setup("2GF99****F66A",{
    locale: 'it_IT',
    environment:'sandbox',
    container:'paypal'
});
}   

BillingPage.ui.xml

    <g:HTMLPanel>
      <div class="container">
        <a id='paypal' href="http://166.78.8.98/cgi-bin/aries.cgi?        sandbox=1&amp;direct=1&amp;returnurl=http://166.78.8.98/cgi-bin/return.htm&amp;cancelurl=http://166.78.8.98/cgi-bin/cancel.htm">  

    </a>
</div>
</g:HTMLPanel>

BillingPage.java

public interface JsResources extends ClientBundle {
    final JsResources INSTANCE = GWT.create(JsResources.class);
    @Source("openPopupExpressCheckoutPayPal.js")
    TextResource scriptOpenPopupPaypal();
}
public BillingPage() {
    initWidget(uiBinder.createAndBindUi(this));
        .
        .
        .

    GWT.log("ScriptInject"+JsResources.INSTANCE.scriptOpenPopupPaypal().getText());
    ScriptInjector.fromString(JsResources.INSTANCE.scriptOpenPopupPaypal().getText()).inject();     
             ScriptInjector.fromUrl("http://www.paypalobjects.com/api/checkout.js").inject  ();


}

I think that I have to add the script directly into the HTMLPanel because unless the script won't find the id="paypal" but I don't know how to do it. Thanks for the attention!

Reference here: https://developer.paypal.com/docs/classic/express-checkout/in-context/integration/


Solution

  • createAndBindUi will just build the DOM subtree, but it won't attach to the document (and reachable through a getElementById). This will only happen when your BillingPage widget is added to another widget that's (recursively) added to the RootPanel (or equivalent), also known as being "attached" to the document.

    That means you should just move your ScriptInjector call to the widget's onLoad, and make sure you do it only once in the event the widget is later detached and reattached (isOrWasAttached() should be false the first time; otherwise use your own boolean flag).

    You also have to inject the script into the "top window" where your UI live; by default ScriptInjector will inject into the hidden iframe where the GWT code runs: you have to add .setWindow‌​(ScriptInjector.TOP_WINDOW) to your ScriptInjector calls.