Last active
February 7, 2024 10:27
-
-
Save Kugelschieber/55233aa918cb9b39352b5857ef21bed2 to your computer and use it in GitHub Desktop.
Tracking internal links using custom events
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function addLinks() { | |
const links = document.getElementsByTagName("a"); | |
for (const link of links) { | |
if (!link.hasAttribute("pirsch-ignore") && !link.classList.contains("pirsch-ignore")) { | |
addInternalLink(link); | |
} | |
} | |
} | |
function addInternalLink(link) { | |
const url = getURL(link.href); | |
if (url !== null && url.hostname === location.hostname) { | |
link.addEventListener("click", () => pirsch(outboundLinkEventName, {meta: {url: url.href}})); | |
link.addEventListener("auxclick", () => pirsch(outboundLinkEventName, {meta: {url: url.href}})); | |
} | |
} | |
function getURL(href) { | |
try { | |
return new URL(href); | |
} catch { | |
return null; | |
} | |
} | |
addLinks(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment