Skip to content

[Bug] trackEvent() on a link is being interrupted and doesn't complete #22

@DigitalMarkethingz

Description

@DigitalMarkethingz

Is this a bug or am I doing something wrong: when I fire a plausible.trackEvent() on a link element, it is not registered because the call gets interrupted by the actual page load behind the link.

Image

In the current situation in my app, I would need to wrap each trackEvent() on link elements with a short timeouts and then manually direct the click to the actual link target. That can't be it, right?

This doesn't work (as per situation explained):

<a id="button-signup" href="/signup" data-placement="footer" title="Click to signup">
   <i name="megaphone"></i> Signup
</a>

<script>
const signupButton = document.querySelector('#button-signup');
    signupButton?.addEventListener('click', (e) => {
        // Event tracking
        try {
            const eventData = { component: 'footer', path: window.location.pathname };
            plausible && plausible.trackEvent('Click CTA Signup', { props: eventData, callback: () => console.debug('trackEvent: Click CTA Signup') });
        } catch (error) {
            console.error('Event tracking error:', error);
        }
    });
</script>

This "workaround" with huge overhead, works:

<a id="button-signup" href="/signup" data-placement="footer" title="Click to signup">
   <i name="megaphone"></i> Signup
</a>

<script>
    const signupButton = document.querySelector('#button-signup');
    signupButton?.addEventListener('click', (e) => {
        e.preventDefault();

        // Event tracking
        try {
            const eventData = { component: 'footer', path: window.location.pathname };
            const targetHref = e.currentTarget.href;

            // Use sendBeacon for reliable tracking before navigation
            const trackingPromise = new Promise((resolve) => {
                plausible.trackEvent('Click CTA Signup', {
                    props: eventData,
                    callback: () => {
                        console.debug('trackEvent: Click CTA Signup');
                        resolve();
                    }
                });
            });

            // Navigate after a short delay to ensure tracking is sent
            setTimeout(() => {
                window.location.href = targetHref;
            }, 50);

        } catch (error) {
            console.error('Event tracking error:', error);
            // If tracking fails, still navigate
            window.location.href = e.currentTarget.href;
        }
    });
</script>

This behaviour is not present in the - outdated - npm plausible-tracker from the official Plausible Team.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions