/
index.js
111 lines (103 loc) · 2.67 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
import React from "react"
import PropTypes from "prop-types"
const createFunctionWithTimeout = (callback, optTimeout = 1000) => {
let called = false
const raceCallback = () => {
if (!called) {
called = true
callback()
}
}
setTimeout(raceCallback, optTimeout)
return raceCallback
}
function OutboundLink(props) {
const { eventCategory, eventAction, eventLabel, eventValue, ...rest } = props
return (
<a
{...rest}
onClick={e => {
if (typeof props.onClick === `function`) {
props.onClick(e)
}
let redirect = true
if (
e.button !== 0 ||
e.altKey ||
e.ctrlKey ||
e.metaKey ||
e.shiftKey ||
e.defaultPrevented
) {
redirect = false
}
if (props.target && props.target.toLowerCase() !== `_self`) {
redirect = false
}
if (window.ga) {
window.ga(`send`, `event`, {
eventCategory: eventCategory || `Outbound Link`,
eventAction: eventAction || `click`,
eventLabel: eventLabel || props.href,
eventValue,
transport: redirect ? `beacon` : ``,
hitCallback: function () {
if (redirect) {
document.location = props.href
}
},
})
} else {
if (redirect) {
document.location = props.href
}
}
return false
}}
/>
)
}
OutboundLink.propTypes = {
href: PropTypes.string,
target: PropTypes.string,
eventCategory: PropTypes.string,
eventAction: PropTypes.string,
eventLabel: PropTypes.string,
eventValue: PropTypes.number,
onClick: PropTypes.func,
}
/**
* This allows the user to create custom events within their Gatsby projects.
*
* @param {import('gatsby-plugin-google-analytics').CustomEventArgs} args
* @see https://developers.google.com/analytics/devguides/collection/analyticsjs/field-reference#events
*/
function trackCustomEvent({
category,
action,
label,
value,
nonInteraction = false,
transport,
hitCallback,
callbackTimeout = 1000,
}) {
if (typeof window !== `undefined` && window.ga) {
const trackingEventOptions = {
eventCategory: category,
eventAction: action,
eventLabel: label,
eventValue: value,
nonInteraction: nonInteraction,
transport,
}
if (hitCallback && typeof hitCallback === `function`) {
trackingEventOptions.hitCallback = createFunctionWithTimeout(
hitCallback,
callbackTimeout
)
}
window.ga(`send`, `event`, trackingEventOptions)
}
}
export { OutboundLink, trackCustomEvent }