How can I add Discourse variables to plugin javascript?


(Travis) #1

Hello, I’m trying to integrate KISSmetrics as a plugin. Adding javascript to the head via the customizations setting is a no-brainer but I think I need to pluginize it since it requires some user variables.

First I need to insert the code into the javascript:

var _kmq = _kmq || [];
var _kmk = _kmk || 'SITESETTINGS_VARIABLE_FOR_KISSMETRICS_API_KEY';
function _kms(u){
  setTimeout(function(){
    var d = document, f = d.getElementsByTagName('script')[0],
    s = d.createElement('script');
    s.type = 'text/javascript'; s.async = true; s.src = u;
    f.parentNode.insertBefore(s, f);
  }, 1);
}
_kms('//i.kissmetrics.com/i.js');
_kms('//doug1izaerwt3.cloudfront.net/' + _kmk + '.1.js');

There’s then the issue of adding the API variables: http://support.kissmetrics.com/apis/javascript/#asynchronous-api

// Identifies the current person as DISCOURSE_USERNAME for future events
_kmq.push(['identify', 'DISCOURSE_USERNAME']);

Something like this should ideally be added upon the user signing in at the start of their session.

How can I put these in plugin.rb or perhaps as a template asset in the plugin folder (?) to get this working? Any help is appreciated!


(Kane York) #2

For the discourse username, you can do Discourse.User.currentProp('username'). This will be undefined for anons. For the API key, you can do SiteSettings.kiss_metrics_key if you create a site_settings.yml file in your plugin.

However, you could probably do all this as just HTML Head Javascript without using a plugin.


(Travis) #3

Is there a trick to getting _kmq.push(['identify', Discourse.User.currentProp('username')]); to work using the HTML Head customizations that I’m missing? That’s why I figured I would have to use a plugin.

If I can insert the variables into the head somehow then that will work just fine.


(Kane York) #4

Just stick the code in a <script> tag, with a setTimeout(function() { ... }, 2); around it.


(Travis) #5

I feel like I must be missing something. I put exactly that in the HTML Head section with the script tag and I get… exactly that output in the HTML. Shouldn’t the output actually contain the username of the user loading it if it’s possible for this to work without a plugin?


(Kane York) #6

But the Javascript knows the username of the user loading it. See your avatar in the upper right? It’s loaded through Discourse.User.current().

Try running that in your console.


(Travis) #7

Interesting, I wonder why KISSmetrics isn’t getting the username info.


(Kane York) #8

Try inserting a debugger; statement there. (Make sure to only preview that, don’t deploy that. If you need to, create a new customization for testing.)