Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

163
Views
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 .

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

<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);
    }
    
});
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!