Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

146
Vistas
How to execute function when anchor tag was opened?

I want to send a post request (with a payload) to my server when a user opens a link in my React app.

My current approach is to use the onClick and onAuxClick callbacks, and then filter out right-clicks (because those don't directly open links).

<a href={link} target="_blank" rel="noopener noreferrer" 
onClick={onLinkClicked} onAuxClick={onLinkClicked}>
    <FaExternalLinkAlt className={styles.headerButton} />
</a>
function onLinkClicked(event: MouseEvent) {
    if ([0,1].includes(event.button)) {
        alert('track click')
    }
}

However, right clicks followed by opening the link via the context menu are also ignored.

Another option seems to be to use the ping callback. However, there are two problems with this: Ping doesn't seem to contain a payload/body, which I need. And browser support seems to be flaky.

How can I reliably track link clicks without false positives and without ignoring opening the link via the context menu (and any other ways of opening a link)?

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

You can force the link to be opened even if the user clicks the wrong button and with that you ensure the actual click count

Edit 1:

For some reason, the contextmenu event fires twice so I advise that you handle that issue I tried removing the event propagation and investigating on it and found nothing

const a  = document.querySelector('a');

//              left,     right,         middle      Clicks
const events = ['click', 'contextmenu', 'auxclick'] // You can add more events if you feel the need to

const cb = (clickType, elem) => {
  console.log(clickType);
  console.log(elem.href);
  
  // Open link and do the post request here
}


events.forEach(eve => {
  a.addEventListener(eve, (e) => {
      e.preventDefault();
      cb(e.which, a);

  })

})
<a href="https://stackoverflow.com/">click</a>

about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda