GoSquared People integration - how to get user name and email in Javascript at <head> customization?

Hi, Geoff from GoSquared here.

We use Discourse ourselves and have of course integrated GoSquared with it.

Thanks to @Chopper for the good example on identifying with user properties. We’ve built on this approach and come up with a snippet of code which also captures the visitor’s pageviews as they browse around the discourse site:

<script type="text/discourse-plugin" version="0.4">
  !function(g,s,q,r,d){r=g[r]=g[r]||function(){(r.q=r.q||[]).push(
  arguments)};d=s.createElement(q);q=s.getElementsByTagName(q)[0];
  d.src='//d1l6p2sc9645hc.cloudfront.net/tracker.js';q.parentNode.
  insertBefore(d,q)}(window,document,'script','_gs');

  // replace GSN-your-token with your site token
  _gs('GSN-your-token', false);

  api.onPageChange((path, title) => _gs('track', path, title));

  $(document).ready(() => {
    const currentUser = api.getCurrentUser();
    if (!currentUser) return;

    $.ajax({
      type: 'GET',
      cache: false,
      url: `/users/${currentUser.username}/activity.json`,
      dataType: 'json',
      xhrFields: {
        'withCredentials': true
      },
      success: result => {
        const user = result.user;
        // map discourse props to GS special props
        const map = {
          id: 'id',
          email: 'email',
          name: 'name',
          username: 'username',
          created_at: 'created_at'
        };

        const props = {};
        const custom = {};

        for (let p in user) {
          let gsName = map[p];
          if (gsName) props[gsName] = user[p];
          else custom[p] = user[p];
        }

        props.custom = custom;

        _gs('identify', props);
      }
    });
  });
</script>

Make sure you place your actual site token in the _gs() function call. Also remove any existing GoSquared integration code otherwise you might double-track.

This snippet uses the client plugin API to listen for page navigation events and trigger GoSquared pageviews. It also pulls the username from existing state to cut out one of the ajax calls.

This is something we’ve put together after a cursory look into Discourse’s APIs, there may well be a better way. If there is, we’d love to hear it!

4 Likes