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)?
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
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>