npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

@d-cat/tag-template-google-analytics

v1.2.0

Published

D-CAT Google Analytics Main Tag Template.

Downloads

54

Readme

Getting started with @d-cat/tag-template-google-analytics

codecov

Tag template to initialize Google Analytics. The template is designed to use as template and inherit from it.

Install

npm i @d-cat/tag-template-google-analytics

Usage

The constructor accepts 1 parameter: a trackers object array, with the following keys:

| parameter | type | description | | -------------- | -------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | fieldsObject | {Object} | The fieldsObject key accepts all google analytics fieldsObject key value pairs. | | optionsToSet | {Object} | optionsToSet object is used to handle tracker updates. There are 3 options: setAlways: this object is always send together with a hit, setOnce: will send object only once, setPageview: will send the given object with each pageview. | | trackerName | String | Name of the tracker | | universalId | String | Google Analytics Property ID. |

The render method is the main method of the class. In the render method, all other methods, with the exception of init, create and listen, are invoked. It's meant as a default setup, however you can either override the behavior of each method to fit your needs or call the methods according your own specs.

import GoogleAnalytics from '@d-cat/tag-template-google-analytics';

const mySyncTrackers = () => {
  const TRACKERS = new GoogleAnalytics([
    {
      fieldsObject: {
        allowLinker: true,
      },
      trackerName: 'vodafone',
      universalId: 'UA-123456-1',
    },
  ]);

  return TRACKERS.render();
};

init: void

The init method injects the Google Analytics script in the head of a webpage.

Without the Google Analytics script loaded, all other methods will not work.

Example

const myInitFunction = (): void => {
  return TRACKERS.init();
};

create(trackers?: ITracker[]): Promise<{ [index:string]: UniversalAnalytics.Tracker }>

The create method, creates a Google Analytics tracker for each tracker you passed.

Example

const myAsynCreateFunction = async (): Promise<UniversalAnalytics.Tracker> => {
  return await TRACKERS.create(); // Promise<{'vodafone': { allowLinker: true, universalId: 'UA-123456-1', }}>
};

listen({trackers?: ITracker[], categories?: RegExp[]}): void

The listen method implements a general DDM listen handler at ga.event trigger.

Example

const myListenFunction = (): void => {
  return TRACKERS.listen(); // undefined
};

updateTrackerOnce({ trackerName, fieldsObject, isUpdateTrackerOnce }: IUpdateTrackerOnce): Promise<boolean>

The updateTrackerOnce method has a default working, but it's expected to override the behavior. This method will be invoked in the render method. By default it only sets the location field of the tracker using DDM.

NOTE: fieldsObject is a function that should return a fieldsObject object, as described by Google Analytics specs.

Example

import GoogleAnalytics from '@d-cat/tag-template-google-analytics';

class MyGoogleAnalyticsVariant extends GoogleAnalytics {
  constructor(...args: any[]) {
    super(...args);
  }

  public async updateTrackerOnce(...args: any[]) {
    await super.updateTrackerOnce(...args);

    // your custom logic
    console.log('updatet..');

    return true;
  }
}

const myCustomTracker = async () => {
  const TRACKERS = new MyGoogleAnalyticsVariant([
    {
      fieldsObject: {
        allowLinker: true,
      },
      trackerName: 'vodafone',
      universalId: 'UA-123456-1',
    },
  ]);

  TRACKERS.init();

  await TRACKERS.create();

  return await TRACKERS.updateTrackerOnce(); // updatet..
};

updateTrackerOnEachHit<T>({ trackerName, fieldsObject }: IUpdateTrackerOnEachHit): Promise<T>

The updateTrackerOnEachHit method has a default working but is meant to override. This method will be invoked in the render method, more specific in this.customTask that's executed as customTask. By default it only sets the page field of the tracker using DDM.

NOTE: fieldsObject is a function that should return a fieldsObject object, as described by Google Analytics specs.

Example

import GoogleAnalytics from '@d-cat/tag-template-google-analytics';

class MyGoogleAnalyticsVariant extends GoogleAnalytics {
  constructor(...args: any[]) {
    super(...args);
  }

  public async updateTrackerOnEachHit(args: any[]) {
    super.updateTrackerOnEachHit(...args);

    // your custom logic
    console.log('updatet..');

    return true;
  }
}

const myCustomTracker = async () => {
  const TRACKERS = new MyGoogleAnalyticsVariant([
    {
      fieldsObject: {
        allowLinker: true,
      },
      trackerName: 'vodafone',
      universalId: 'UA-123456-1',
    },
  ]);

  TRACKERS.init();

  await TRACKERS.create();

  return await TRACKERS.updateTrackerOnEachHit(); // updatet..
};

updateTrackerOnEachPageView<T>(fieldsObject: IFieldsObject): Promise<T>

The updateTrackerOnEachPageView method has a default working but is meant to override. This method will be invoked in the render method. By default it appends the pageview object passed within optionsToSet to the pageview hit.

NOTE: fieldsObject is a function that should return a fieldsObject object, as described by Google Analytics specs.

Example

import GoogleAnalytics from '@d-cat/tag-template-google-analytics';

class MyGoogleAnalyticsVariant extends GoogleAnalytics {
  constructor(...args: any[]) {
    super(...args);
  }

  public async updateTrackerOnEachPageView() {
    return {
      page: 'https://vodafone.nl',
    };
  }
}

const myCustomTracker = async () => {
  const TRACKERS = new MyGoogleAnalyticsVariant([
    {
      fieldsObject: {
        allowLinker: true,
      },
      trackerName: 'vodafone',
      universalId: 'UA-123456-1',
    },
  ]);

  TRACKERS.init();

  await TRACKERS.create();

  return await TRACKERS.updateTrackerOnEachPageView(); // { page: 'https://vodafone.nl' }
};

customTask<T>({ fieldsObject, model, trackerName, updateTrackerOnEachHit }: ICustomTask): Promise<T>

The customTask method has a default working but is meant to override. This method will be invoked in the render method, more specific in the customTask. By default it executes the updateTrackerOnEachHit and verifies if a specific cookie value has been set in DDM.

NOTE: fieldsObject is a function that should return a fieldsObject object, as described by Google Analytics specs.

Example

import GoogleAnalytics from '@d-cat/tag-template-google-analytics';

class MyGoogleAnalyticsVariant extends GoogleAnalytics {
  constructor(...args: any[]) {
    super(...args);
  }

  public async customTask(...args: any[]) {
    super.customTask(...args);
    console.log('send something');
  }
}

const myCustomTracker = async () => {
  const TRACKERS = new MyGoogleAnalyticsVariant([
    {
      fieldsObject: {
        allowLinker: true,
      },
      trackerName: 'vodafone',
      universalId: 'UA-123456-1',
    },
  ]);

  TRACKERS.init();

  await TRACKERS.create();

  return await TRACKERS.customTask(); // send something..
};

requirePlugins(trackerName: string, plugins?: string[]): void

The requirePlugins method has a default working. It requires all given plugins. By default this are ec and displayfeatures.

Example

import GoogleAnalytics from '@d-cat/tag-template-google-analytics';

const mySyncPlugin = async () => {
  const TRACKERS = new GoogleAnalytics([
    {
      fieldsObject: {
        allowLinker: true,
      },
      trackerName: 'vodafone',
      universalId: 'UA-123456-1',
    },
  ]);

  TRACKERS.init();

  await TRACKERS.create();

  return TRACKERS.requirePlugins('vodafone', ['ec']);
};

campaignSetup({ trackerName, regex }: ICampaignSetup): void

The campaignSetup method has a default working, it's meant to override. By default it sends campaign data to Google Analytics.

Example

import GoogleAnalytics from '@d-cat/tag-template-google-analytics';

const mySyncPlugin = async () => {
  const trackerName = 'vodafone';

  const TRACKERS = new GoogleAnalytics([
    {
      fieldsObject: {
        allowLinker: true,
      },
      trackerName,
      universalId: 'UA-123456-1',
    },
  ]);

  TRACKERS.init();

  await TRACKERS.create();

  return TRACKERS.campaignSetup({ trackerName });
};

setUserId<T>(clientId: T, key?: string): Promise<T>

The setUserId method sets an user ID persistent in DDM.

Example

import GoogleAnalytics from '@d-cat/tag-template-google-analytics';

const myAsyncPlugin = async () => {
  const TRACKERS = new GoogleAnalytics([
    {
      fieldsObject: {
        allowLinker: true,
      },
      trackerName: 'vodafone',
      universalId: 'UA-123456-1',
    },
  ]);

  return await TRACKERS.setUserId('1');
};

hitCallBack<T>({ clientId, storageId, trackerName }: IHitCallBack): Promise<T>

The hitCallBack method is executed as Google Analytics HitCallBack.

Example

import GoogleAnalytics from '@d-cat/tag-template-google-analytics';

const myAsyncPlugin = async () => {
  const TRACKERS = new GoogleAnalytics([
    {
      fieldsObject: {
        allowLinker: true,
      },
      trackerName: 'vodafone',
      universalId: 'UA-123456-1',
    },
  ]);

  return await TRACKERS.hitCallBack({ clientId, storageId, trackerName }); // will execute directly after a pageview
};

sendPageView({ clientId, fieldsObject, storageId, trackerName }: ISendPageView): void

The sendPageView method sends a pageview to Google Analytics and invokes this.hitCallBack after the pageview has been send.

Example

import GoogleAnalytics from '@d-cat/tag-template-google-analytics';

const myAsyncPlugin = async () => {
  const TRACKERS = new GoogleAnalytics([
    {
      fieldsObject: {
        allowLinker: true,
      },
      trackerName: 'vodafone',
      universalId: 'UA-123456-1',
    },
  ]);

  return TRACKERS.sendPageView({ clientId, storageId, trackerName }); // invokes hitCallBack
};

render(trackers?: ITracker[]): void

The render method invokes all other methods in a fixed order. You can override the behavior, but it's recommended to override other methods instead.

Render explained

class GoogleAnalytics {
  public render(...args: any[]): void {
    // make sure always, once and pageview
    // do not break, when no callbacks are passed
    const fallBack: () => Partial<models.IFieldsObject> = () => {
      return {};
    };

    // Google Analytics is either synchronous (web)
    // or async when using the Google Analytics mock
    ga(async () => {
      // start with a try to catch any error
      // while initializing google analytics
      try {
        // for each of the defined trackers, destructure
        for (const { optionsToSet = {}, trackerName, universalId } of trackers) {
          // make sure all fieldsObjects are available as function
          const { setAlways = fallBack, setOnce = fallBack, setPageview = fallBack } = optionsToSet;

          // get the current tracker by name
          const tracker = ga.getByName(trackerName);

          // get the current clientId
          const clientId = tracker.get('clientId') as string;

          // set the storageId
          const storageId = `${universalId}:clientid`;

          // if there is an object passed to update once
          // update it once
          this.isUpdateTrackerOnce = await this.updateTrackerOnce({
            trackerName,
            fieldsObject: setOnce,
            isUpdateTrackerOnce: this.isUpdateTrackerOnce,
          });

          // setting the customTask
          // the customTask runs before each hit
          tracker.set(
            'customTask',
            async (model: models.ITrackerModel): Promise<void> => {
              await this.customTask({ fieldsObject: setAlways, model, trackerName });
            },
          );

          // push the user.ids.ga_ids in the dataLayer
          // to keep track of all of them
          await this.setUserId(clientId);

          // Inform Google Analytics we would like to use the ecommerce and display feature plugins
          this.requirePlugins(trackerName);

          // if the url contains a specific query string
          // forward this url to google analytics
          this.campaignSetup({ trackerName });

          // send the pageview to google analytics and assign hit
          this.sendPageView({
            trackerName,
            clientId,
            storageId,
            fieldsObject: await this.updateTrackerOnEachPageView(setPageview),
          });
        }
      } catch (err) {
        throw new Error(`Error during initializing Google Analytics: ${err}`);
      }
    });
  }
}