Search code examples
javascriptgwtgoogle-analyticsjsni

Send event to Google Analytics from GWT using JSNI


I have all the Google Analytics code between the and in my HTML file. These stats are processed correctly.

After a onclick event on my , function below is called and I would like to send an event to Google Analytics, but it is never received. What am I doing wrong?

public static native void googleAnalyticsEvent(String boxId) /*-{
_gaq.push(['_trackEvent', boxId , 'Click']);
}-*/;

FYI, if I replace this code for the below, an alert is correctly displayed:

public static native void googleAnalyticsEvent(String boxId) /*-{
alert(boxId);
}-*/;

Solution

  • Try:

    public static native void googleAnalyticsEvent(String boxId) /*-{
        $wnd._gaq.push(['_trackEvent', boxId , 'Click']);
    }-*/;
    

    From https://developers.google.com/web-toolkit/doc/1.6/DevGuideCodingBasics#DevGuideJavaScriptNativeInterface

    "Note that the code did not reference the JavaScript window object directly inside the method. When accessing the browser's window and document objects from JSNI, you must reference them as $wnd and $doc, respectively. Your compiled script runs in a nested frame, and $wnd and $doc are automatically initialized to correctly refer to the host page's window and document."