0

I wrote a Web Method which will be called on unload event of jQuery. It is running when I run through Visual Studio. I deployed in IIS. It is also working when I execute application in IE and Firefox. When I run the application in Chrome, it strangely doesn't fire up unload event. Below is what I have written:

  <script type="text/javascript" language="javascript">
    var startTime;

    $(window).load(function () {
        startTime = new Date().getTime();
    });

    $(window).unload(function () {
        var endTime = new Date().getTime();
        var diff = new Date(endTime - startTime);
        var path = window.location.pathname.toString();

            $.ajax({
                type: "POST",
                url: path + "/LogUserActivity",
                data: "{ 'timeSpent': '" + Math.floor(diff / 1000).toString() + "', 'urlVisited': '" + path + "'}",
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: function () {
                },
                error: function (xhr, status, error) {
                },
                failure: function () {
                }
            });
    });

</script>
techspider
  • 3,370
  • 13
  • 37
  • 61

1 Answers1

1

Credit goes to @Daniel A. White

It is not an issue with jQuery unload but with AJAX sync call.

Made my AJAX call to sync instead of async, which worked on Chrome as well as all other browsers.

 $.ajax({
                async: false,
                type: "POST",
                url: path + "/LogUserActivity",
                data: "{ 'timeSpent': '" + Math.floor(diff / 1000).toString() + "', 'urlVisited': '" + path + "'}",
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: function () {
                },
                error: function (xhr, status, error) {
                    var err = eval("(" + xhr.responseText + ")");
                    alert(err.Message);
                },
                failure: function () {
                }
            });
techspider
  • 3,370
  • 13
  • 37
  • 61