Add event listener to modal close In Drupal we can open a modal is two ways, either with HTML:
&lt;a class=&quot;use-ajax profile-page-link&quot; data-dialog-type=&quot;modal&quot; href=&quot;/node/1&quot; data-dialog-options=&quot;{&amp;quot;width&amp;quot;:800}&quot;&gt;Open Modal&lt;/a&gt;

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?
The clue was seeing the Drupal's modal just uses jquery widgets. So a simple Google for &quot;jquery widget close event&quot; lead me to this SO answer.
So the solution is:
$('#drupal-modal').on('dialogclose', function(event) {
    alert('closed');
});