plausible / plausible-tracker

Frontend library to interact with Plausible Analytics
https://github.com/plausible/plausible-tracker
MIT License
214 stars 46 forks source link

Fix page reloads on missing hrefs #28

Open jozsefsallai opened 2 years ago

jozsefsallai commented 2 years ago

Added a check for the href attribute to the anchor link click event listener.

Description

Since the package updates the event listener of all anchor links on the website, sometimes we might not want the behavior of the new event listener to run. In this specific example, if an anchor tag doesn't have a href attribute, the page would just reload. Sometimes the lack of href tags is intentional. For example, the hamburger menu in Buefy's navigation component looks like this:

<a role="button" aria-label="menu" class="navbar-burger burger"> ... </a>

In this scenario, the hamburger anchor opens the menu but then the page reloads. My change makes sure the href attribute actually exists before doing anything.

Related Issue

N/A

Screenshots or GIFs (if appropriate):

N/A

Types of changes

Checklist:

obviyus commented 2 years ago

@ukutaht if you have a moment, it would be great to have this fix merged.

ionicsolutions commented 1 year ago

I ran into the exact same issue and would love for this to be merged so that we can enable outbound link tracking for our sites without breaking the mobile menu.

<a> tags without href are valid HTML but there is nothing to track there.

jozsefsallai commented 1 year ago

I ran into the exact same issue and would love for this to be merged so that we can enable outbound link tracking for our sites without breaking the mobile menu.

<a> tags without href are valid HTML but there is nothing to track there.

@ionicsolutions As a temporary workaround if you use Node.js tooling, you can use patch-package to manually fix the issue. The files you will likely need to patch are:

Adding the following line to the beginning of the trackClick function should fix the issue:

if (!this.href) return;
ionicsolutions commented 1 year ago

Thanks, @jozsefsallai, I implemented the workaround you suggested and it works like a charm.