user695022
user695022

Reputation: 589

How do I use a possibly undefined global object with JsInterop?

The host page for my 3rd party app may have a global object window.PageObject. If it's present, my app needs to use its properties and functions, also if present. I've come up with a solution using JsInterop, but it requires multiple method declarations per property/function:

@JsType(isNative=true, namespace=JsPackage.GLOBAL, name="PageObject")
public class PageObject {

    private PageObject PageObject() {}

    // called by every single public method
    @JsProperty(namespace=JsPackage.GLOBAL, name="PageObject")
    private static native boolean __isDefined();

    // each property has a native accessor
    @JsProperty(name="some_property")
    private static native String _getSomeProperty();

    // each property also has an overlay method that checks __isDefined()
    @JsOverlay
    public static String getSomeProperty() {
        return __isDefined() ? _getSomeProperty() : null;
    }

    // calling a function safely requires an additional check to see if it exists
    @JsProperty(name="some_procedure")
    private static boolean _hasSomeProcedure();

    @JsMethod(name="some_procedure")
    private static native void _someProcedure();

    @JsOverlay
    public static void someProcedure() {
        if (__isDefined() && _hasSomeProcedure()) {
            _someProcedure();
        }
    }

}

Am I missing some part of JsInterop that handles this better? Is there another solution that's easier to use (excluding JSNI)?

Upvotes: 1

Views: 671

Answers (2)

jofeu
jofeu

Reputation: 75

To check the presense of window.PageObject you could do the following:

  1. Create a JsInterop wrapper for the JavaScript variable 'window'

    @JsType(isNative=true, namespace=JsPackage.GLOBAL, name="window")
    public class JsWindowWrapper {
        public static Object PageObject;
    }
    
  2. Check if window.PageObject is defined

    if (null != JsWindowWrapper.PageObject) { ... };
    

Upvotes: 2

Thomas Broyer
Thomas Broyer

Reputation: 64541

How about using an instance of PageObject?

Make a static getter to retrieve the instance out and then you can check for null before calling methods (like you'd do in JS).

Now if you really want some static API that are no-op / return null when the object is not defined, then you don't have much choice and need to write a wrapper anyway (like you'd do in JS)

Upvotes: 3

Related Questions