bosskovic
bosskovic

Reputation: 2054

how to add a basic keen.io event with javascript

I am trying to set up a basic example that sends a custom keen.io event via js. At the moment I do not need any presentation, visualisation, etc.

Here is the example that I created from another one I found online. I attempted several variations, and all of them work in Google Chrome, but none of them works in Firefox (38.0 for Ubuntu canonical - 1.0).

  1. if I add to the head the inline script (!function(a,b){a("Keen"...) as it is proposed in the manual, I do not get any errors in FF, but it seems that addEvent never gets called and it produces no response, "err" nor "res".

  2. if I include the library from the CDN (d26b395fwzu5fz.cloudfront.net/3.2.4/keen.min.js), I get an error when the page is loaded:

    ReferenceError: Keen is not defined
    var keenClient = new Keen({

  3. If I download the js file and serve it locally, after the button is clicked, I get the following error response:

    Error: Request failed
    err = new Error(is_err ? res.body.message : 'Unknown error occurred');

All of these attempts work from Chrome, but I need this to work from other browsers too.

Upvotes: 4

Views: 615

Answers (1)

bosskovic
bosskovic

Reputation: 2054

I received a response from keen.io team. It turned out that Adblock Plus is interfering with the script. After I disabled it everything works in FF as in Chrome.


After some investigation in turned out that request to http://api.keen.io was blocked by "EasyPrivacy" filter of ABP with these filter rules: keen.io^$third-party,domain=~keen.github.io|~keen.io

So, sending a request to an "in-between" server (a proxy) seems to be the only solution that I can see.


We have a bit specific use case - a need to track a static site and also an available access to a rails api server, but the solution we ended up using may come useful to someone.

error.html

<html>
<head>
  <title>Error</title>
  <script src="/js/vendor/jquery-1.11.2.min.js"></script>
  <script src="/js/notification.js"></script>
  <script type="text/javascript">
    $(document).on('ready', function () {
      try {
        $.get(document.URL).complete(function (xhr, textStatus) {
          var code = xhr.status;
          if (code == 200) {
            var codeFromPath = window.location.pathname.split('/').reverse()[0].split('.')[0];
            if (['400', '403', '404', '405', '414', '416', '500', '501', '502', '503', '504'].indexOf(codeFromPath) > -1) {
              code = codeFromPath;
            }
          }
          Notification.send(code);
        });
      }
      catch (error) {
        Notification.send('error.html', error);
      }
    });
  </script>
</head>
<body>
There was an error. Site Administrators were notified.
</body>
</html>

notification.js

var Notification = (function () {

  var endpoint = 'http://my-rails-server-com/notice';

  function send(type, jsData) {
    try {
      if (jsData == undefined) {
        jsData = {};
      }

      $.post(endpoint, clientData(type, jsData));
    }
    catch (error) {
    }
  }

  //  private
  function clientData(type, jsData) {
    return {
      data: {
        type: type,
        jsErrorData: jsData,
        innerHeight: window.innerHeight,
        innerWidth: window.innerWidth,
        pageXOffset: window.pageXOffset,
        pageYOffset: window.pageYOffset,
        status: status,
        navigator: {
          appCodeName: navigator.appCodeName,
          appName: navigator.appName,
          appVersion: navigator.appVersion,
          cookieEnabled: navigator.cookieEnabled,
          language: navigator.language,
          onLine: navigator.onLine,
          platform: navigator.platform,
          product: navigator.product,
          userAgent: navigator.userAgent
        },

        history: {
          length: history.length
        },
        document: {
          documentMode: document.documentMode,
          documentURI: document.documentURI,
          domain: document.domain,
          referrer: document.referrer,
          title: document.title,
          URL: document.URL
        },
        screen: {
          width: screen.width,
          height: screen.height,
          availWidth: screen.availWidth,
          availHeight: screen.availHeight,
          colorDepth: screen.colorDepth,
          pixelDepth: screen.pixelDepth
        },
        location: {
          hash: window.location.hash,
          host: window.location.host,
          hostname: window.location.hostname,
          href: window.location.href,
          origin: window.location.origin,
          pathname: window.location.pathname,
          port: window.location.port,
          protocol: window.location.protocol,
          search: window.location.search
        }
      }
    }
  }

  return {
    send: send
  }
}());

example of sending notification manually from js code:

try {
  // some code that may produce an error
}
catch (error) {
  Notification.send('name of keen collection', error);
}

rails

# gemfile
gem 'keen'

#routes
resource :notice, only: :create

#controller
class NoticesController < ApplicationController

  def create
    # response to Keen.publish does not include an ID of the newly added notification, so we add an identifier
    # that we can use later to easily track down the exact notification on keen
    data = params['data'].merge('id' => Time.now.to_i)

    Keen.publish(data['type'], data) unless dev?(data)

    # we send part of the payload to a company chat, channel depends on wheter the origin of exception is in dev or production
    ChatNotifier.notify(data, dev?(data)) unless data['type'] == '404'
    render json: nil, status: :ok
  end

  private

  def dev?(data)
    %w(site local).include?(data['location']['origin'].split('.').last)
  end
end

Upvotes: 3

Related Questions