How to create tracking pixel with Google Analytics for 3rd party site?

10,859

Solution 1

If the 3rd-party site has analytics.js already running then using that client ID is probably best. You can get it by doing the following:

var cid;
ga(function(tracker) {
  cid = tracker.get('clientId'));
});

If analytics.js is not running, or if you can't access the ga variable for some reason, you can just generate the client ID randomly. This is approximately what Google does. It's a random 31-bit integer with the current date string appended:

var cid = Math.floor(Math.random() * 0x7FFFFFFF) + "." +
          Math.floor(Date.now() / 1000);

Solution 2

Only to complement @Philip Walton excellent answer, Google Analytics expects a random UUID (version 4) as the Client ID, according to the official Documentation.

Client ID

Required for all hit types.

This anonymously identifies a particular user, device, or browser instance. For the web, this is generally stored as a first-party cookie with a two-year expiration. For mobile apps, this is randomly generated for each particular instance of an application install. The value of this field should be a random UUID (version 4) as described in http://www.ietf.org/rfc/rfc4122.txt

@broofa provided a simple way to generate a RFC4122-compliant UUID in JavaScript here. Quoting it here for the sake of completeness:

'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
    var r = Math.random()*16|0, v = c == 'x' ? r : (r&0x3|0x8);
    return v.toString(16);
});
Share:
10,859
Vlad
Author by

Vlad

Analyst + Designer

Updated on June 14, 2022

Comments

  • Vlad
    Vlad almost 2 years

    We need to track conversions that happen on a 3rd party site. The only thing we can place on that site is an image pixel and maybe some JS logic for when to fire it.

    I know it is possible to fire a conversion using the Measurement Protocol: https://developers.google.com/analytics/devguides/collection/protocol/v1/parameters#visitor

    Ideally, I'd just give the 3rd party an IMG url and that would be it. The problem is the CID (unique client id).

    I can try passing the CID from our site to the 3rd party via URL parameter. However, there are many cases where its not available (e.g., IMG pixcel will be in an email, the goal URL is on printed literature) or the 3rd party is not willing to go through the hassle. Is it best practice to pass this CID in this way?

    I can try generating a CID, but I can't find a dead simple way of doing that e.g., var CID = generateCID(). The 3rd party site has its own GA on the page. Can I just take their Google Analytics CID and use it in the image pixel URL?

    What the best way to do this? Thank you!