Skip to content

Commit

Permalink
Merge pull request #114 from ynmstudio/feature/update-app-to-angular-17
Browse files Browse the repository at this point in the history
fix: update useOutboundClickListener()
  • Loading branch information
denisyilmaz authored Feb 28, 2024
2 parents a9de4f1 + 5a743ec commit dabd648
Showing 1 changed file with 40 additions and 42 deletions.
82 changes: 40 additions & 42 deletions landingpage/src/providers/matomo/utils/useOutboundClickListener.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -2,48 +2,46 @@ import { useOnDocument, $, useContext } from "@builder.io/qwik";
import MatomoContext from "../MatomoContext";

function useOutboundClickListener() {
const { instance } = useContext(MatomoContext);

const handleOutboundClick = $((event: Event) => {
// The target is not guaranteed to be a link, it could be a child element.
// Look up the element's parent until the anchor element is found.
const findLinkElement = (
el: EventTarget | null
): HTMLElement | null => {
if (el instanceof HTMLAnchorElement && el.href) {
return el;
}
if (el instanceof HTMLElement && el.parentElement) {
return findLinkElement(el.parentElement);
}
return null;
};

const target = findLinkElement(event.target);

if (!(target instanceof HTMLAnchorElement)) {
return;
}

const { href } = target;

// Check if the click target differs from the current hostname, meaning it's external
if (
/* @ts-ignore */
!href.match(
new RegExp(
`^(http://www.|https://www.|http://|https://)+(${window.location.hostname})`
)
)
) {
instance?.trackLink({ href });
}
});

useOnDocument(
"click",
$((event) => handleOutboundClick(event))
);
const { matomo } = useContext(MatomoContext);

const handleOutboundClick = $((event: Event) => {
// The target is not guaranteed to be a link, it could be a child element.
// Look up the element's parent until the anchor element is found.
const findLinkElement = (el: EventTarget | null): HTMLElement | null => {
if (el instanceof HTMLAnchorElement && el.href) {
return el;
}
if (el instanceof HTMLElement && el.parentElement) {
return findLinkElement(el.parentElement);
}
return null;
};

const target = findLinkElement(event.target);

if (!(target instanceof HTMLAnchorElement)) {
return;
}

const { href } = target;

// Check if the click target differs from the current hostname, meaning it's external
if (
/* @ts-ignore */
!href.match(
new RegExp(
`^(http://www.|https://www.|http://|https://)+(${window.location.hostname})`,
),
)
) {
matomo?.trackLink({ href });
}
});

useOnDocument(
"click",
$((event) => handleOutboundClick(event)),
);
}

export default useOutboundClickListener;

0 comments on commit dabd648

Please sign in to comment.