Add event listener to modal close

In Drupal we can open a modal is two ways, either with HTML:

<a class="use-ajax profile-page-link" data-dialog-type="modal" href="http://drupal.stackexchange.com/node/1" data-dialog-options="{&quot;width&quot;:800}">Open Modal</a>

Or with JS:

let ajaxSettings = {
  url: 'node/1',
  dialogType: 'modal',
  dialog: { width: 800 },
};
let ajaxObject = Drupal.ajax(ajaxSettings);
ajaxObject.execute();

Once the modal is open I would like to attach an event to the close button so I can drop a cookie on the close event to show the visitor has seen the modal and not show it to them again.

The close button has the class ui-dialog-titlebar-close but this is added after the initial page load so to attach an event we would need a dynamic click handler such as:

$('body').on('click', '.ui-dialog-titlebar-close', function() {
    alert('close button was clicked 2');
});

However this event never fires. This ctools issue mentions the same thing and has a solution involving binding to the CToolsCloseModalBehaviors event, however that was 6 years ago and I’m using D9 with no ctools so need to find a new solution.

When I inspect the attached events on the close button I can see jquery.ui/ui/widget-min.js r() and an anonymous function in jquery.min.js. Using non minified vs would help but not sure how to do that?