my english is not good. sorry.
I want developing a CMS with php. And I want to change the on_desk database column to 1 when the post edit page is opened and the on_desk column to be 0 when exiting same page
By doing this while you are in the Edit Post window tab. I want to prevent the same page from opening in a new window.
I used the following solution. But sometimes it doesn't work well. For example, when I cancel the dialog, it does not work well Do you have another solution? For example, the way not to use beforeunload.
Javascript|jQuery:
function clearDesk(){
    $.post('clearOnDesk.php',{
        "id":parseInt($('body').attr('data-pageId')),
    }, function(){
       $('body').attr('data-desk',1)
    });
} 
function setDesk(){
    $.post('setOnDesk.php',{
        "id":parseInt($('body').attr('data-pageId')),
    }, function(){
       $('body').attr('data-desk',2)
    });
}
setDesk();
const beforLoadFunc = function beforLoadFunc () {
   clearDesk();
   if(parseInt($('body').attr('data-desk')) == 1){
       setTimeout(() => {
               window.addEventListener('mousemove', (e) => {
                   setDesk();
               });
       }, 1000);
   }  
}
window.addEventListener('beforeunload', function onBeforeUnload(e) {
   setTimeout(beforLoadFunc, 500);
   const dialogText = 'are you sure?';
   e.returnValue = dialogText;
   return dialogText;
});
clearOnDesk.php
 if($_POST)
 {
    $id = (int)$this->post('id');
    if($id && $id != '')
    {
        $w['id'] = $id;
    } else die("die!");
    $d['on_desk'] = 1;
    $this->db->update('post',$d,$w,["i","i"]);
    //update on_desk to 0 for (post row) in database by (pageId).
    //by PHP Prepared Statements
}
setOnDesk.php
 if($_POST)
 {
    $id = (int)$this->post('id');
    if($id && $id != '')
    {
        $w['id'] = $id;
    } else die("die!");
    $d['on_desk'] = 2;
    $this->db->update('post',$d,$w,["i","i"]);
    // update on_desk to 1 for (poster row) in database by (pageId).
    //by PHP Prepared Statements
 }