javascript - How to make a backup of Database automatically once on clicking 'X' button of browser?

one text

Hope someone advise,

I have a code using PHP which is making a backup of my database on logging out of my session but I need also to make a backup once I click the 'X' button right top of the browser using JS I guess.

Also I tried to use onunload / onbeforeunload / onclose functions but every click in any another page in the app it making a backup but I just want the backup while closing the page.

I know it's a complicated case but It's the best way I've used to keep my database backing up automatically once I left the app.

Here is the PHP code of backing up database:

        $databases = ['laligacafe']; //Database name
        $user = "root";
        $pass = "";
        $host = "localhost";

        date_default_timezone_set('Africa/Cairo');

        if(!file_exists("C:/xampp/htdocs/LaLigaCafe/assets/sql_backups")){
            mkdir("C:/xampp/htdocs/LaLigaCafe/assets/sql_backups");
        }

        foreach($databases as $database){
            if(!file_exists("C:/xampp/htdocs/LaLigaCafe/assets/sql_backups/$database")){
                mkdir("C:/xampp/htdocs/LaLigaCafe/assets/sql_backups/$database");
            }

            $filename = $database."_".date("F_d_Y")."@".date("g_ia").uniqid("_", false);
            $folder = "C:/xampp/htdocs/LaLigaCafe/assets/sql_backups/$database/".$filename.".sql";

            exec("C:/xampp/mysql/bin/mysqldump --user={$user} --password={$pass} --host={$host} {$database} --result-file={$folder}", $output);
        }

Thanks in advance.

Source