(function() {
  var d = document.currentScript && document.currentScript.getAttribute('data-domain');
  if (!d) d = location.hostname;

  function send(path, ref) {
    var payload = {
      domain: d,
      path: path,
      referrer: ref || document.referrer || ''
    };
    var url = '/api/st';
    if (navigator.sendBeacon) {
      navigator.sendBeacon(url, JSON.stringify(payload));
    } else {
      fetch(url, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(payload), keepalive: true });
    }
  }

  send(location.pathname, document.referrer);

  var _push = history.pushState;
  history.pushState = function() {
    _push.apply(history, arguments);
    send(location.pathname, '');
  };
  window.addEventListener('popstate', function() {
    send(location.pathname, '');
  });
})();
