goat-counter.js 8.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269
  1. // GoatCounter: https://www.goatcounter.com
  2. // This file (and *only* this file) is released under the ISC license:
  3. // https://opensource.org/licenses/ISC
  4. ;(function() {
  5. 'use strict';
  6. if (window.goatcounter && window.goatcounter.vars) // Compatibility with very old version; do not use.
  7. window.goatcounter = window.goatcounter.vars
  8. else
  9. window.goatcounter = window.goatcounter || {}
  10. // Load settings from data-goatcounter-settings.
  11. var s = document.querySelector('script[data-goatcounter]')
  12. if (s && s.dataset.goatcounterSettings) {
  13. try { var set = JSON.parse(s.dataset.goatcounterSettings) }
  14. catch (err) { console.error('invalid JSON in data-goatcounter-settings: ' + err) }
  15. for (var k in set)
  16. if (['no_onload', 'no_events', 'allow_local', 'allow_frame', 'path', 'title', 'referrer', 'event'].indexOf(k) > -1)
  17. window.goatcounter[k] = set[k]
  18. }
  19. var enc = encodeURIComponent
  20. // Get all data we're going to send off to the counter endpoint.
  21. var get_data = function(vars) {
  22. var data = {
  23. p: (vars.path === undefined ? goatcounter.path : vars.path),
  24. r: (vars.referrer === undefined ? goatcounter.referrer : vars.referrer),
  25. t: (vars.title === undefined ? goatcounter.title : vars.title),
  26. e: !!(vars.event || goatcounter.event),
  27. s: [window.screen.width, window.screen.height, (window.devicePixelRatio || 1)],
  28. b: is_bot(),
  29. q: location.search,
  30. }
  31. var rcb, pcb, tcb // Save callbacks to apply later.
  32. if (typeof(data.r) === 'function') rcb = data.r
  33. if (typeof(data.t) === 'function') tcb = data.t
  34. if (typeof(data.p) === 'function') pcb = data.p
  35. if (is_empty(data.r)) data.r = document.referrer
  36. if (is_empty(data.t)) data.t = document.title
  37. if (is_empty(data.p)) data.p = get_path()
  38. if (rcb) data.r = rcb(data.r)
  39. if (tcb) data.t = tcb(data.t)
  40. if (pcb) data.p = pcb(data.p)
  41. return data
  42. }
  43. // Check if a value is "empty" for the purpose of get_data().
  44. var is_empty = function(v) { return v === null || v === undefined || typeof(v) === 'function' }
  45. // See if this looks like a bot; there is some additional filtering on the
  46. // backend, but these properties can't be fetched from there.
  47. var is_bot = function() {
  48. // Headless browsers are probably a bot.
  49. var w = window, d = document
  50. if (w.callPhantom || w._phantom || w.phantom)
  51. return 150
  52. if (w.__nightmare)
  53. return 151
  54. if (d.__selenium_unwrapped || d.__webdriver_evaluate || d.__driver_evaluate)
  55. return 152
  56. if (navigator.webdriver)
  57. return 153
  58. return 0
  59. }
  60. // Object to urlencoded string, starting with a ?.
  61. var urlencode = function(obj) {
  62. var p = []
  63. for (var k in obj)
  64. if (obj[k] !== '' && obj[k] !== null && obj[k] !== undefined && obj[k] !== false)
  65. p.push(enc(k) + '=' + enc(obj[k]))
  66. return '?' + p.join('&')
  67. }
  68. // Show a warning in the console.
  69. var warn = function(msg) {
  70. if (console && 'warn' in console)
  71. console.warn('goatcounter: ' + msg)
  72. }
  73. // Get the endpoint to send requests to.
  74. var get_endpoint = function() {
  75. var s = document.querySelector('script[data-goatcounter]')
  76. if (s && s.dataset.goatcounter)
  77. return s.dataset.goatcounter
  78. return (goatcounter.endpoint || window.counter) // counter is for compat; don't use.
  79. }
  80. // Get current path.
  81. var get_path = function() {
  82. var loc = location,
  83. c = document.querySelector('link[rel="canonical"][href]')
  84. if (c) { // May be relative or point to different domain.
  85. var a = document.createElement('a')
  86. a.href = c.href
  87. if (a.hostname.replace(/^www\./, '') === location.hostname.replace(/^www\./, ''))
  88. loc = a
  89. }
  90. return (loc.pathname + loc.search) || '/'
  91. }
  92. // Run function after DOM is loaded.
  93. var on_load = function(f) {
  94. if (document.body === null)
  95. document.addEventListener('DOMContentLoaded', function() { f() }, false)
  96. else
  97. f()
  98. }
  99. // Filter some requests that we (probably) don't want to count.
  100. goatcounter.filter = function() {
  101. if ('visibilityState' in document && document.visibilityState === 'prerender')
  102. return 'visibilityState'
  103. if (!goatcounter.allow_frame && location !== parent.location)
  104. return 'frame'
  105. if (!goatcounter.allow_local && location.hostname.match(/(localhost$|^127\.|^10\.|^172\.(1[6-9]|2[0-9]|3[0-1])\.|^192\.168\.|^0\.0\.0\.0$)/))
  106. return 'localhost'
  107. if (!goatcounter.allow_local && location.protocol === 'file:')
  108. return 'localfile'
  109. if (localStorage && localStorage.getItem('skipgc') === 't')
  110. return 'disabled with #toggle-goatcounter'
  111. return false
  112. }
  113. // Get URL to send to GoatCounter.
  114. window.goatcounter.url = function(vars) {
  115. var data = get_data(vars || {})
  116. if (data.p === null) // null from user callback.
  117. return
  118. data.rnd = Math.random().toString(36).substr(2, 5) // Browsers don't always listen to Cache-Control.
  119. var endpoint = get_endpoint()
  120. if (!endpoint)
  121. return warn('no endpoint found')
  122. return endpoint + urlencode(data)
  123. }
  124. // Count a hit.
  125. window.goatcounter.count = function(vars) {
  126. var f = goatcounter.filter()
  127. if (f)
  128. return warn('not counting because of: ' + f)
  129. var url = goatcounter.url(vars)
  130. if (!url)
  131. return warn('not counting because path callback returned null')
  132. var img = document.createElement('img')
  133. img.src = url
  134. img.style.position = 'absolute' // Affect layout less.
  135. img.style.bottom = '0px'
  136. img.style.width = '1px'
  137. img.style.height = '1px'
  138. img.loading = 'eager'
  139. img.setAttribute('alt', '')
  140. img.setAttribute('aria-hidden', 'true')
  141. var rm = function() { if (img && img.parentNode) img.parentNode.removeChild(img) }
  142. img.addEventListener('load', rm, false)
  143. document.body.appendChild(img)
  144. }
  145. // Get a query parameter.
  146. window.goatcounter.get_query = function(name) {
  147. var s = location.search.substr(1).split('&')
  148. for (var i = 0; i < s.length; i++)
  149. if (s[i].toLowerCase().indexOf(name.toLowerCase() + '=') === 0)
  150. return s[i].substr(name.length + 1)
  151. }
  152. // Track click events.
  153. window.goatcounter.bind_events = function() {
  154. if (!document.querySelectorAll) // Just in case someone uses an ancient browser.
  155. return
  156. var send = function(elem) {
  157. return function() {
  158. goatcounter.count({
  159. event: true,
  160. path: (elem.dataset.goatcounterClick || elem.name || elem.id || ''),
  161. title: (elem.dataset.goatcounterTitle || elem.title || (elem.innerHTML || '').substr(0, 200) || ''),
  162. referrer: (elem.dataset.goatcounterReferrer || elem.dataset.goatcounterReferral || ''),
  163. })
  164. }
  165. }
  166. Array.prototype.slice.call(document.querySelectorAll("*[data-goatcounter-click]")).forEach(function(elem) {
  167. if (elem.dataset.goatcounterBound)
  168. return
  169. var f = send(elem)
  170. elem.addEventListener('click', f, false)
  171. elem.addEventListener('auxclick', f, false) // Middle click.
  172. elem.dataset.goatcounterBound = 'true'
  173. })
  174. }
  175. // Add a "visitor counter" frame or image.
  176. window.goatcounter.visit_count = function(opt) {
  177. on_load(function() {
  178. opt = opt || {}
  179. opt.type = opt.type || 'html'
  180. opt.append = opt.append || 'body'
  181. opt.path = opt.path || get_path()
  182. opt.attr = opt.attr || {width: '200', height: (opt.no_branding ? '60' : '80')}
  183. opt.attr['src'] = get_endpoint() + 'er/' + enc(opt.path) + '.' + enc(opt.type) + '?'
  184. if (opt.no_branding) opt.attr['src'] += '&no_branding=1'
  185. if (opt.style) opt.attr['src'] += '&style=' + enc(opt.style)
  186. if (opt.start) opt.attr['src'] += '&start=' + enc(opt.start)
  187. if (opt.end) opt.attr['src'] += '&end=' + enc(opt.end)
  188. var tag = {png: 'img', svg: 'img', html: 'iframe'}[opt.type]
  189. if (!tag)
  190. return warn('visit_count: unknown type: ' + opt.type)
  191. if (opt.type === 'html') {
  192. opt.attr['frameborder'] = '0'
  193. opt.attr['scrolling'] = 'no'
  194. }
  195. var d = document.createElement(tag)
  196. for (var k in opt.attr)
  197. d.setAttribute(k, opt.attr[k])
  198. var p = document.querySelector(opt.append)
  199. if (!p)
  200. return warn('visit_count: append not found: ' + opt.append)
  201. p.appendChild(d)
  202. })
  203. }
  204. // Make it easy to skip your own views.
  205. if (location.hash === '#toggle-goatcounter') {
  206. if (localStorage.getItem('skipgc') === 't') {
  207. localStorage.removeItem('skipgc', 't')
  208. alert('GoatCounter tracking is now ENABLED in this browser.')
  209. }
  210. else {
  211. localStorage.setItem('skipgc', 't')
  212. alert('GoatCounter tracking is now DISABLED in this browser until ' + location + ' is loaded again.')
  213. }
  214. }
  215. if (!goatcounter.no_onload)
  216. on_load(function() {
  217. // 1. Page is visible, count request.
  218. // 2. Page is not yet visible; wait until it switches to 'visible' and count.
  219. // See #487
  220. if (!('visibilityState' in document) || document.visibilityState === 'visible')
  221. goatcounter.count()
  222. else {
  223. var f = function(e) {
  224. if (document.visibilityState !== 'visible')
  225. return
  226. document.removeEventListener('visibilitychange', f)
  227. goatcounter.count()
  228. }
  229. document.addEventListener('visibilitychange', f)
  230. }
  231. if (!goatcounter.no_events)
  232. goatcounter.bind_events()
  233. })
  234. })();