plausible-tracker icon indicating copy to clipboard operation
plausible-tracker copied to clipboard

Fix page reloads on missing hrefs

Open jozsefsallai opened this issue 2 years ago • 4 comments

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

  • [x] Bug fix (non-breaking change which fixes an issue)
  • [ ] New feature (non-breaking change which adds functionality)
  • [ ] Breaking change (fix or feature that would cause existing functionality to change)

Checklist:

  • [x] My code follows the code style of this project.
  • [ ] My change requires a change to the documentation.
  • [ ] I have updated the documentation accordingly.
  • [x] I have read the CONTRIBUTING document.
  • [ ] I have added tests to cover my changes.
  • [x] All new and existing tests passed.

jozsefsallai avatar Apr 09 '22 00:04 jozsefsallai

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

obviyus avatar Aug 01 '22 05:08 obviyus

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 avatar Feb 18 '23 12:02 ionicsolutions

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:

  • node_modules/plausible-tracker/build/main/lib/tracker.js
  • node_modules/plausible-tracker/build/module/lib/tracker.js

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

if (!this.href) return;

jozsefsallai avatar Feb 18 '23 14:02 jozsefsallai

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

ionicsolutions avatar Feb 18 '23 15:02 ionicsolutions