Skip to content
Advertisement

How i call a server function after close browser tab or browser in JavaScript

How i call a server function after close window tab or window in JavaScript.

Like this image

//This is my server code

public ActionResult DeleteNotPostedImage(string folder , string PostID)
    {
        folder = folder.Replace('_', '-');
        string message = string.Empty;

        try
        {
            if (Convert.ToInt32(PostID) <= 0)
            {
                if(Directory.Exists(Server.MapPath(string.Format("/ViewSolution/{0}", folder))))
                {
                    Directory.Delete(Server.MapPath(string.Format("/ViewSolution/{0}", folder)), true);
                }
            }

            return Json(new { success = true, message = message }, JsonRequestBehavior.AllowGet);
        }
        catch (Exception ex)
        {
            MSError.Trace(ex);
        }
        return Json(new { success = false, message = message }, JsonRequestBehavior.AllowGet);
    }

I want to call this function after close browser tab or browser .

Advertisement

Answer

<script type="text/javascript">

var contentStatus = false;
$(document).ready(function () {
    
    var checkAction = "";

    $('#your-post-btn').bind("click", function () {

        checkAction = "Save";
        $(this).data("clicked", true);
    });      

    // on refresh 
    window.onbeforeunload = function(){
        if($('#your-post-btn').data('clicked'))
        {
            checkAction = "Save";
            return null;
        } else {
            checkAction = "Refresh";
            return "Are you sure to leave this page";
        }
    };
    
    // window close or tab close
    window.onunload= function(){
        if(checkAction.toLowerCase() !== "save"){
            Test2();
        }
    };

    function Test2(){
        console.log(checkAction);
        var formData = new FormData();
        formData.append("folder",folder-name);
        formData.append("PostID", post-id);
        formData.append("action", checkAction);
        var url = window.location.protocol.concat('//',window.location.host) + "/view/DeleteNotPostedImage";
        window.navigator.sendBeacon(url, formData);
    }
    
});
User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement