None of the pure JS solutions I've been able to find have worked for me, at least not with all three of the browsers that I use to test my code: FF/Chrome/Edge.
So I developed (perhaps a dirty) solution with jQuery+JS+PHP.
Maybe somebody has come with a similar solution, but I was not able to find one.
The button that closes the tab/window (of course, it must be opened by JS) has the following click
event that creates a hidden field (uniquely named) before it submits the form.
$(".cancel").on('click', function (){
var $form = $(this).closest('form');
$form.append($("<input>", { type:'hidden', name: "cancel", value: ''}));
$form.submit();
})
At the top of the PHP script I have the following code
if (isset($_POST['cancel'])){
?><script>window.close();</script><?php
exit;
};
This solution has been tested with FF 98 and Chrome/Edge 99. If the page doesn't have a form, it can be created with the previous event.
Just in case the page has more than one forms and they submit to different pages, just add $form.attr({target: "_self", action: ''});
in the event!