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