Search code examples
jqueryjquery-pluginsonbeforeunload

jQuery beforeunload cancel with submit for firefox


I am having a heck of a time with this one guys. I am trying to alert someone if they are trying to leave a page and have uploaded files already. The tricky part is I want it to not warn them if they are submitting. This is the strange part, the code I'm going to put in works in chrome but all the other browsers don't like it. It is part of a plugin so just ignore some of the code.

  function cleanFiles(obj){
   var $obj = $(obj),
   $jForm = $obj.parents("form");
   $jForm.find("input[type=button]:last").not($obj).bind("click.save", function(event){
    $(window).unbind('beforeunload.cleanFile unload.removeFiles');
   });
   $(window).bind('beforeunload.cleanFile', function(event){
    var localSettings = $.extend({}, settings),
    filesList = "";
    $("input[type=hidden].fileFieldLists").each(function(){
     var $obj = $(this);
     filesList += ($obj.val() || "");
    });
    if(filesList.length){
     return localSettings.defaultLeaveMessage;
    }
    $(window).bind('unload.removeFiles', function(event){
     var filesList = [];
     $("input[type=hidden].fileFieldLists").each(function(){
      var $obj = $(this),
       localSettings = $.extend({}, settings, $obj.next().data()),
       fieldValues = ($obj.val().indexOf("*") ? $obj.val().split("*") : $obj.val()),
       fieldValuesCnt = fieldValues.length;
       for(var i = 0; i < fieldValuesCnt; i++){
        filesList.push(localSettings.filepath + fieldValues[i]);
       }
     });
     if(filesList.length){
      deleteFiles(filesList.join(","), false);
     }
    });
   });
  }

Solution

  • So I found it. Apparently in IE and Firefox the "click" event is fired after the "beforeUnload" event. However the "mouseup" event fires before both of them so that was my solution. I bound it to "click" and "mouseup" like so

    $jForm.find("input[type=button]:last").not($obj).bind("click.save mouseup.save", function(event){
    

    and it works in all browsers now... man what I would do for browsers to be consistent. Thanks for all the responses.