Skip to content

Commit

Permalink
Merge pull request #272 from hashicorp/pres/fix/link-handler
Browse files Browse the repository at this point in the history
fix(analytics/add-global-handler): check if value exists🔍
  • Loading branch information
prestonbourne authored Jul 11, 2024
2 parents 3435aae + 786a411 commit 1a826a9
Showing 1 changed file with 30 additions and 36 deletions.
66 changes: 30 additions & 36 deletions packages/analytics/add-global-link-handler/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -44,52 +44,46 @@ export function addGlobalLinkHandler(

window.addEventListener('click', (event) => {
const linkElement = (event.target as HTMLElement).closest('a')
const href = linkElement && linkElement.getAttribute('href')
if (!href || !containsDestination(href)) return

if (
linkElement &&
containsDestination(
(linkElement as HTMLAnchorElement).attributes.getNamedItem('href')!
.value
)
) {
const segmentAnonymousId = getSegmentId()
const productIntent = getProductIntentFromURL()
const utmParams = getUTMParamsCaptureState()
const segmentAnonymousId = getSegmentId()
const productIntent = getProductIntentFromURL()
const utmParams = getUTMParamsCaptureState()

const url = new URL(linkElement.href)
const url = new URL(linkElement.href)

// Safegaurd against absolute URLs that are on the same domain origin
if (window.location.origin === url.origin) {
return
}
// Safegaurd against absolute URLs that are on the same domain origin
if (window.location.origin === url.origin) {
return
}

event.preventDefault()
event.preventDefault()

if (segmentAnonymousId) {
url.searchParams.set('ajs_aid', segmentAnonymousId)
}
if (segmentAnonymousId) {
url.searchParams.set('ajs_aid', segmentAnonymousId)
}

if (productIntent) {
url.searchParams.set('product_intent', productIntent)
}
if (productIntent) {
url.searchParams.set('product_intent', productIntent)
}

if (Object.keys(utmParams).length > 0) {
for (const [key, value] of Object.entries(utmParams)) {
url.searchParams.set(key, value)
}
if (Object.keys(utmParams).length > 0) {
for (const [key, value] of Object.entries(utmParams)) {
url.searchParams.set(key, value)
}
}

callback && callback(url.href)
callback && callback(url.href)

if (
linkElement.getAttribute('target') === '_blank' ||
event.ctrlKey ||
event.metaKey
) {
window.open(url.href, '_blank')
} else {
location.href = url.href
}
if (
linkElement.getAttribute('target') === '_blank' ||
event.ctrlKey ||
event.metaKey
) {
window.open(url.href, '_blank')
} else {
location.href = url.href
}
})

Expand Down

0 comments on commit 1a826a9

Please sign in to comment.