Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

145
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda