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

@oddcamp/tracking-util

v1.1.0

Published

GDPR compliant tracking

Downloads

4

Readme

Odd Camp Tracking Utility

GDPR compliant tracking.

Supported services

  • Google Tag Manager (GTM)
  • Google Analytics (GA)

Example codes

Usual workflow

<div class="consent-dialog" hidden>
  <p>Do you wanna get tracked?</p>
  <p>
    <button type="button" data-type="accept">Accept</button>
    <button type="button" data-type="deny">Deny</button>
  </p>
</div>
import TrackingUtil from "@oddcamp/tracking-util"

// Initiates util, automatically inserts scripts and starts tracking if tracking
// has been previously accepted by user
const tu = new TrackingUtil({
  services: {
    gtm: {
      id: `GTM-XXXX`,
    },
    ga: {
      id: `UA-XXXXX-Y`,
    },
  },
})

const dialogEl = document.querySelector(`.consent-dialog`)

// Displays cookie consent dialog if user hasn't already made a decision
if (tu.userReacted()) {
  dialogEl.removeAttribute(`hidden`)
}

// Sets tracking accepted on button click
dialogEl
  .querySelector(`button[data-type="accept"]`)
  .addEventListener(`click`, () => {
    tu.setTrackingAccepted(true, {
      defaultGTMdataLayer: [{ pageTitle: `Home` }, { event: `pageview` }],
      defaultGAcommands: [
        [`set`, `anonymizeIp`, true],
        [`send`, `pageview`],
      ],
    })
    dialogEl.setAttribute(`hidden`, ``) // Hides the dialog
  })

// Sets tracking denied on button click
dialogEl
  .querySelector(`button[data-type="deny"]`)
  .addEventListener(`click`, () => {
    tu.setTrackingAccepted(false)
    dialogEl.setAttribute(`hidden`, ``) // Hides the dialog
  })

Tracking clicks

Once TrackingUtil instance is created it also becomes accessible via window.trackingUtil, e.g.:

document.querySelector(`a.logo`).addEventListener(`click`, () => {
  if (window.trackingUtil) {
    window.trackingUtil.registerGTMdata({
      event: `Click`,
      eventCategory: `Links`,
      eventLabel: `Logo`,
    })

    window.trackingUtil.runGAcommand([
      `send`,
      `event`,
      {
        eventCategory: `Links`,
        eventAction: `Click`,
        eventValue: `Logo`,
      },
    ])
  }
})

Tracking categories with Google Tag Manager

You may want to allow the user to choose how advanced tracking they are fine with:

<div class="consent-dialog" hidden>
  <!-- ... -->
  <label><input type="checkbox" name="performance" /> Performance</label>
  <label><input type="checkbox" name="marketing" /> Marketing</label>
  <label><input type="checkbox" name="analytics" /> Analytics</label>
  <!-- ... -->
</div>
// ...
dialogEl
  .querySelector(`button[data-type="accept"]`)
  .addEventListener(`click`, () => {
    const defaultGTMdataLayer = [{ event: `pageview` }]

    if (dialogEl.querySelector(`input[name="performance"]`).checked)
      defaultGTMdataLayer.push({ event: `trackingCategory:performance` })

    if (dialogEl.querySelector(`input[name="marketing"]`).checked)
      defaultGTMdataLayer.push({ event: `trackingCategory:marketing` })

    if (dialogEl.querySelector(`input[name="analytics"]`).checked)
      defaultGTMdataLayer.push({ event: `trackingCategory:analytics` })

    tu.setTrackingAccepted(true, { defaultGTMdataLayer })

    dialogEl.setAttribute(`hidden`, ``)
  })
// ...

Default options

{
  /*
    If `false` tracking scripts aren't inserted and no tracking is performed.
    Useful if you need to disable tracking in `development` environment.
  */
  enabled: true,

  /* Cookie options */
  cookie: {
    name: `tracking-util-reacted`,
    options: {
      path: `/`,
      maxAge: 3600 * 24 * 30 * 12, // year
      secure: false,
    },
  },

  /* Services */
  services: {

    /* Google Tag Manager options */
    gtm: {
      /* E.g.: GTM-XXXX */
      id: ``,

      /* Data layer name. Usually it's `dataLayer`, i.e. `window.dataLayer` */
      dataLayerName: `dataLayer`,
    },

    /* Google Analytics options */
    gtm: {
      /* E.g.: UA-XXXX-Y */
      id: ``,

      /* Command queue name. Usually it's `ga`, i.e. `window.ga` */
      commandQueue: `ga`,

      /*
        Fields for `create` method. For example:

          createFields: {
            name: `myTracker`,
            alwaysSendReferrer: true,
          }

        ...is equal to:

          window.ga('create', 'UA-XXXX-Y', { name: `myTracker`, alwaysSendReferrer: true })

        All options available at
          https://developers.google.com/analytics/devguides/collection/analyticsjs/field-reference#create
      */
      createFields: {},
    },
  },
}

Methods

/*
 * Checks if user has made a decision to allow or deny tracking
 * @returns {bool}
 */
userReacted()

/*
 * Checks if tracking has been accepted by user
 * @returns {bool}
 */
trackingAccepted()

/*
 * Sets tracking decision and starts tracking if accepted
 *
 * @param {bool} value `true` if accepted, `false` if denied
 * @param {object} options
 *   @param defaultGTMdataLayer {array} Default GTM data layer
 *   @param defaultGAcommands {array} Default GA data
 */
setTrackingAccepted(value, (options = {}))

If tracking was accepted by user the defaultGTMdataLayer/defaultGAcommands are saved in a cookie (Options → cookie.name) and the data is automatically injected in GTM's data layer every time TrackingUtil instance is created. Therefore it's useful for tracking page views and storing other default information. Check out /example for demo.


/*
 * Registers GTM data
 *
 * @param {object} data
 * @returns {bool} `true` on success and `false` on failure
 */
registerGTMdata(data)

// e.g.: registerGTMdata({ event: `click` })

Doesn't do anything if tracking hasn't been accepted by user.


/*
 * Gets registered GTM data
 * @returns {array}
 */
registeredGTMdata()

/*
 * Registers GA data
 *
 * @param {array} data
 */
runGAcommand(data)

// e.g.: runGAcommand([`send`, `event`, `click`, `download-me`, { transport: `beacon` }])

// All options available at
//   https://developers.google.com/analytics/devguides/collection/analyticsjs/field-reference#general

Doesn't do anything if tracking hasn't been accepted by user.

Local development and testing

$ yarn dev or $ yarn build

TODO

  • [ ] Support functions in defaultGTMdataLayer and defaultGAcommands
  • [ ] Support multiple trackers
  • [x] Support Google Analytics