beyonk-group / svelte-google-analytics

Google Analytics component for Svelte
77 stars 12 forks source link

Add configurations prop for configuring Google Property ID:s #5

Closed oskarhane closed 3 years ago

oskarhane commented 3 years ago

As discussed in #4.

This is useful in Sapper where only the initial page view is automatically sent on load. After that each page view must be sent manually using: ga.addEvent("page_view", { page_path: path });.

The annoying thing with that is that we must not the send initial page view using ga.addEvent because that one is automatic.

<script>
import { stores } from "@sapper/app";
import { onMount } from "svelte";
import { GoogleAnalytics, ga } from "@beyonk/svelte-google-analytics";

const { page } = stores();
let initialLoad = true;

onMount(() => {
        return page.subscribe(({ path }) => {
          if (!initialLoad) {
              ga.addEvent("page_view", { page_path: path });
          } else {
              initialLoad = false;
          }
      });
  });
</script>

<GoogleAnalytics properties={['UA-XXXX-X']} />

This PR fixes so that we can configure Google Analytics not to send anything automatically and just rely on ga.addEvent and remove the initialLoad guard:

<script>
import { stores } from "@sapper/app";
import { onMount } from "svelte";
import { GoogleAnalytics, ga } from "@beyonk/svelte-google-analytics";

const { page } = stores();

onMount(() => {
        return page.subscribe(({ path }) => {
              ga.addEvent("page_view", { page_path: path });
      });
  });
</script>

<GoogleAnalytics properties={['UA-XXXX-X']} configurations={{'UA-XXXX-X': { 'send_page_view': false }}} />

See https://developers.google.com/analytics/devguides/collection/gtagjs#disable_pageview_measurement for reference docs.