Pregunta

I'm trying to use Google's javascript API in my GWT application (to use google visualizations) and I'm having trouble referencing the google object in my JSNI. I'm getting a javascript error: "google is not defined".

I'm aware there's a GWT wrapper API for this but it doesn't have the functionality I need. I followed all the suggestions here: use visualization api of google in GWT but I'm still getting this error.

I've added this line to my gwt.xml file:

<script src="https://www.google.com/jsapi"></script>

I'm not sure where to put it so I added it below my main tag. That other stack question said to add it to add it to my HTML, so I'm assuming this is what they meant.

Here's the stripped down native method I'm calling that's producing the "google is not defined" error:

public static native void nativeJavaScriptFunction() /*-{
    google.load('visualization', '1.0', {
        'packages' : [ 'corechart' ]
    });
}-*/;

I've also tried referencing google as "$wnd.google" and "$doc.google". I'm using the latest version of GWT 2.5.1. Does anybody else have any javascript api's working and referenced in a JSNI method?

¿Fue útil?

Solución 2

I figured out a solution. First of all I didn't want to add that script tag to the gwt.xml file. I didn't realize my app had a main HTML file. I added this to the head tag there.

<script type="text/javascript" src="https://www.google.com/jsapi" ></script>

I could then reference the google object in JNSI via $wnd.google. I was still having trouble with the actual load call though. It was causing the page clear and just hang. I decided to try loading the API with this code that I pulled from VisualationUtils from the GWT wrapper API.

AjaxLoaderOptions options = AjaxLoaderOptions.newInstance();
options.setPackages("corechart");
AjaxLoader.loadApi("visualization", "1", new Runnable() {
    @Override
    public void run() {
        jsniCall();
}

This did the trick. I'd still like to know why I can't load the API in the JSNI method but this works for me.

Otros consejos

Instead of adding that script tag in your host page, you could use ScriptInjector instead, like this:

ScriptInjector
    .fromUrl("http://api.elsevier.com/javascript/scopussearch.jsp")
    .setCallback(new Callback<Void, Exception> () {
        @Override
        public void onFailure(Exception reason) {
            throw new UnsupportedOperationException("FAILURE to inject Scopus API !!!");
        }

        @Override
        public void onSuccess(Void result) {
            System.out.println("Elsevier scopus search API successfully injected...");
        }
    }).setWindow(ScriptInjector.TOP_WINDOW).inject();

Then you should be able to successfully use the injected API via JSNI.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top