javascriptformseventsdrupal-form-submission

Submit a form on close tab/window event


I'm wondering if there is a way to submit the contents of a form when the user closes a tab/window. I've looked into the onunload and onbeforeunload events and think maybe this is the road to go down. I've tried

window.onbeforeunload = function(e) { 
  document.getElementById("my-form").submit();
};

but that doesn't work. Is there a way I can get this to work in the way I am describing?


Solution

  • If you can use JQuery, give this a try:

    $(window).bind('beforeunload', function() { 
       $("#id-of-submit-button").click();
    });