How to add google analytics to vaadin application?

I’m using Vaadin 12, with spring boot. I want to add google analytics on my page. The code looks like this:

<script async src="https://www.googletagmanager.com/gtag/js?id=my-id"></script>
<script>
  window.dataLayer = window.dataLayer || [];
  function gtag(){dataLayer.push(arguments);}
  gtag('js', new Date());

  gtag('config', 'my-id');
</script>

How can I add this to the Vaadin’s webpage? I already tryied to use annotation @Inline, but it always put some additional stuff there. So is there a way how to put those scripts to the head of html? I’m using only java classes without HTML pages.

There is add-on project for this. You can find it from GitHub here:

https://github.com/samie/vaadin-ga-tracker

It is not yet published in Directory.

This will not help me. I need to add this script to the head of html page. If this is not possible with vaadin, I will have to look for other web frameworks

Vaadin applications are single page, so to get full benefit of Google Analytics for behavioral tracking of the application use, you need this kind of add-on. It makes possible to have virtual page views, i.e. you can see view level activity in Google Analytics.

For simple integration of the JavaScript in head of html you can use e.g. @Inline annotation, like described here: https://vaadin.com/docs/flow/advanced/tutorial-bootstrap.html However that will not give you view level tracking.

This addon didn’t work, or I was not able to make it working. I did it with @Inline annotation

I did it with @Inline annotation

It is not the correct way. You need to add the add-on dependency to your pom.xml so that maven downloads the artifacts.

<dependency>
   <groupId>org.vaadin.addons</groupId>
   <artifactId>googleanalyticstracker</artifactId>
   <version>4.0.0</version>
</dependency>

Then inspect the demo application how to use it

https://github.com/samie/vaadin-ga-tracker/tree/master/demo/src/main/java/org/vaadin/googleanalytics/tracking/demo

Start with https://github.com/samie/vaadin-ga-tracker/blob/master/demo/src/main/java/org/vaadin/googleanalytics/tracking/demo/MainLayout.java

At minimum You need to atleast

@EnableGoogleAnalytics(value = "your_tracking_id_here")
public class MainLayout extends VerticalLayout implements RouterLayout {
    public MainLayout() {
	    ...
    }
}

I just tried it, and there is some problem with maven dependency. Maven do not know how to resolve it.

Here is my solution
This annotation is on Root. java class
@Inline(value = "analytics.js", target = HEAD, position = PREPEND, wrapping = JAVASCRIPT)

Ad this is the content of analytics.js:

(function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']
=r;i[r]
=i[r]
||function(){
(i[r]
.q=i[r]
.q||[]).push(arguments)},i[r]
.l=1*new Date();a=s.createElement(o),
m=s.getElementsByTagName(o)[0]
;a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
})(window,document,'script','https://www.google-analytics.com/analytics.js','ga');

ga('create', 'my-tracking-id', 'auto');
ga('send', 'pageview');

With this google analytics works, and I can see the statistics.

Hi together,

I have a problem with Vaadin (13.0.1) and the addon from https://vaadin.com/directory/component/googleanalyticstracker too.

What I wanted to achieve is to count people visiting my website and log hits on my login button on my login page for the beginning.

So I added

<dependency>
            <groupId>org.vaadin.addons</groupId>
            <artifactId>googleanalyticstracker</artifactId>
            <version>4.0.0</version>
</dependency>

to my pom.xml

My Loginpage looks like:

@Route(value = "login")
@Caption("Home")
@Icon(VaadinIcon.HOME)
@EnableGoogleAnalytics(value = "UA-ABCDE-1")
public class LoginScreen extends VerticalLayout implements TrackerConfigurator, LocaleChangeObserver, BeforeEnterObserver {


    private LoginService loginService;
    private LoginForm loginForm;

    @Autowired
    public LoginScreen(LoginService loginService) {
        if (VaadinSession.getCurrent().getAttribute(Benutzer.class) != null) {
            return;
        }
        this.loginService = loginService;
        loginForm = new LoginForm();
        loginForm.addLoginListener((ComponentEventListener<AbstractLogin.LoginEvent>) event -> {
            final String username = event.getUsername();
            GoogleAnalyticsTracker.getCurrent().sendEvent("Login", "Login try (User: " + username + ")");
            ............
        });
        loginForm.setForgotPasswordButtonVisible(false);
        add(loginForm);
    }

    @Override
    public void localeChange(LocaleChangeEvent event) {
        loginForm.setI18n(updateLocale());
    }

    private LoginI18n updateLocale() {
        .................
    }

    @Override
    public void beforeEnter(BeforeEnterEvent event) {
        if (VaadinSession.getCurrent().getAttribute(Benutzer.class) != null) {
            event.rerouteTo("");
        }
    }

    @Override
    public void configureTracker(TrackerConfiguration trackerConfiguration) {
        trackerConfiguration.setCreateField("allowAnchor", Boolean.FALSE);
        trackerConfiguration.setInitialValue("transport", "beacon");
        trackerConfiguration.setCookieDomain("none");
    }
}

Now when running the app (localhost:8080/login) the google tag assistant finds the tag but says:

“No HTTP response detected” and “Missing analytics.js script”.

(It says the same when running the example from github)

But in the dev tools I can see:

client-28831013082792340517B7074033EF04.cache.js:183  Processing time was 0ms
analytics_debug.js:24 
                         _                          _       _   _
                        | |                        | |     | | (_)
  __ _  ___   ___   __ _| | ___    __ _ _ __   __ _| |_   _| |_ _  ___ ___
 / _` |/ _ \ / _ \ / _` | |/ _ \  / _` | '_ \ / _` | | | | | __| |/ __/ __|
| (_| | (_) | (_) | (_| | |  __/ | (_| | | | | (_| | | |_| | |_| | (__\__ \
 \__, |\___/ \___/ \__, |_|\___|  \__,_|_| |_|\__,_|_|\__, |\__|_|\___|___/
  __/ |             __/ |                              __/ |
 |___/             |___/                              |___/

analytics_debug.js:24 Running analytics_debug.js. This script is intended for testing and debugging only.
log @ analytics_debug.js:24
analytics_debug.js:24 Initializing Google Analytics.
analytics_debug.js:24 Running command: ga("create", "UA-ABCDE-1", "none", {allowAnchor: false})
analytics_debug.js:24 Creating new tracker: t0
analytics_debug.js:24 New visitor. Generating new clientId
analytics_debug.js:24 Generating new gid
analytics_debug.js:24 Running command: ga("set", {sendHitTask: null, transport: "beacon"})
analytics_debug.js:24 Running command: ga("set", "page", "login")
analytics_debug.js:24 Running command: ga("send", "pageview")
analytics_debug.js:24 Setting throttling cookie: "_gat"
analytics_debug.js:24 Registered new plugin: ga(provide, "render", Function)
client-28831013082792340517B7074033EF04.cache.js:183 Loaded https://www.google-analytics.com/analytics_debug.js

And even if I hit the button I see the corresponding GA-Code executed in the dev tools (see attached screenshot).

But my real time dashboard of GA always shows 0 visitors. Am I missing something here? Any help appreciated. Thanks a lot in advance!

17591598.png
17591601.png

I think the problem is that it is loading analytics_debug.js instead of analytics.js, but I’m unsure why exactly. Have to look deeper.

Thanks for having a look! I wondered about the _debug, too. If I can help by providing additional information on my setup or anything else please let me know.

Didn’t find a way to test the setup myself now, but we discussed with Leif and here is something that you should try:

@EnableGoogleAnalytics(value="UA-ABCDE-1", devLogging = LogLevel.NONE, sendMode = SendMode.ALWAYS)

Maybe the LogLevel.NONE is already enough, but let us know how it goes.

Cool, it works like a charme with

@EnableGoogleAnalytics(value="UA-ABCDE-1", devLogging = LogLevel.NONE, sendMode = SendMode.ALWAYS)

Thanks a lot!

(It seems like sendMode = SendMode.ALWAYS is the relevant one. It works when using both Annotation attributes (devLogging and sendMode) and when using only sendMode. When using only devLogging it is not working.)