0

Let's say a page has a link on it, like:

<a href="https://stackoverflow.com">I'm a link!</a>

If we add jQuery code like:

$('a').on('click', function() {
  // store what link was clicked in database
  console.log('store link clicked in database');
}));

The event would get set off when the user clicks the link.

Would the full on click and ajax code get fully run before leaving the site, every time?

space_food_
  • 800
  • 1
  • 7
  • 23
  • 1
    Does [this](https://stackoverflow.com/questions/1346043/html-anchor-link-href-and-onclick-both) answer your question – Badal Saibo Jul 05 '21 at 03:02

2 Answers2

0

It's probably depends on your database, if it's async, it might not work.

However you can use event.preventDefault() and after database fully saved click the link again:

document.querySelector("a").addEventListener("click", e =>
{
  // is clicked by user?
  if (e.isTrusted)
    e.preventDefault();

  // save to databse
  console.log(e);

  // when finished click the link again
  e.target.click();
});
<a href="https://stackoverflow.com">test</a>
vanowm
  • 9,466
  • 2
  • 21
  • 37
0

You can deal with the situation in multiple ways without preventing the default.

First:

You can have a link without any href and do the redirect on the click callback

<a href='#'>I'm a link!</a>

$('a').on('click', function() {
  // store what link was clicked in database
  $.post('/save', {}).done(function(){
    window.location.href = 'http://stackoverflow.com';
  });
}));

Second:

There is a special api that handles the ajax request reliable on the page unload phase : navigator.sendBeacon https://developer.mozilla.org/en-US/docs/Web/API/Navigator/sendBeacon that improves performance since is non blocking.

var payload;

$('a').on('click', function(e) {
  // Cache what link was clicked
  payload = null; // get info from the event e
}));

document.addEventListener('visibilitychange', function() {
  if (document.visibilityState === 'hidden') {
    navigator.sendBeacon('/save', payload);
  }
});
Tiberiu C.
  • 3,365
  • 1
  • 30
  • 38