blog

Recoving data from Addthis

Long story short, Addthis is a tool that allows you to easily add social media follow and share buttons to your website; we wanted to detect when a user shares a page, follows our page, or comes from a post that was shared on social media. Luckily, Addthis offers a simple API to detect these actions: when you include Addthis in your page, it makes a global object in the window called "addthis", which can be accessed by any other script in the page.

Detecting shares

To detect shares, we listen for an event called "addthis.menu.share" on the addthis object, then we can recover the service (social media) the resource was shared on:

addthis.addEventListener('addthis.menu.share', service => {
    const serviceName = service.data.service;
    console.log(serviceName); // facebook, twitter, etc...
});

Detecting follows

This option was not described in the API, but to my surprise, it actually works!

To detect follows, we listen for an event called "addthis.menu.follow" on the addthis object, just like for shares:

addthis.addEventListener('addthis.menu.follow', service => {
    const serviceName = service.data.service;
    console.log(serviceName); // facebook, twitter, etc...
});

Detecting number of shares of a service

To detect the number of shares in one or more services, you can call the function addthis.sharecounters.getShareCounts, pass an array of strings with the names of the services, and a callback that will receive an array of objects (one for every service you passed) with the number of shares. Say you want the number of shares on 'facebook':

addthis.addthis.sharecounters.getShareCounts(['facebook'], shares => {
    const sharesNo = shares[0].count;
    console.log(sharesNo);
});

Detecting if the user is coming from a shared post

It is useful to know when a user is coming from a post that was shared on facebook, twitter, etc. To get this information, Addthis inserts a URL fragment similar to this one:

http://example.com/blog#AHb4gs1hwck.facebook

Where the last bit of the fragment is the name of the service.

Addthis offers another event listener to recover this information, and this is where things get weird: I really don't see why this should be an event, because it is not an event - it is a "constant" information that should be able to be recovered any time, just like the number of shares. Because of this, we decided that we would parse the information from the url ourselves with a snippet similar to this one:

const url = window.location.href;
const regex = /.+#.+\.([a-zA-Z0-9_-]+)$/;
const result = regex.exec(url);
const serviceName = result[1];

This Regular Expression extracts the last bit of the fragment.

Overall, it is a very easy API, but the documentation could be a lot better and some pieces don't seem to fit together well.