Search code examples
javascriptjquerysharepoint-2013addeventlistener

Save event with an addEventListener beforeunload not firing when add attachments in Sharepoint form


I am using IE11, JavaScript, and SharePoint 2013. There is a main page that opens a new form tab(NewForm.aspx) to add or an edit tab form (EditForm.aspx) to edit a record.

When the user Saves in the new form tab it saves the data, refreshes the main page, and closes the new form tab.

When the user Saves in the edit form tab it saves the data, refreshes the main page, refreshes the edit form tab and stays on that edit form tab record.

This works great with code provided below, except when the user attaches files via the Attach File button in the SP ribbon. It goes into the Save click event, hits the window.addEventListener, and skips over it. The user is defaulted back to the SP library AllItems.aspx list.

I have tried putting code in just the Save click and not in the beforeunload event listener, but then the attachment does not get saved to the item.

I have tried capturing the file attach event ($('input[id=attachOKbutton]')) and adding a beforeunload listener.

Again the issue is to save the record and stay on the EditForm tab, even when the user attaches a file.

$(function() {
  $('input[value=Save]').click(function() {
    window.addEventListener("beforeunload", function(event) {  //does not go in here if file is attached
        var idxForm = location.pathname.indexOf("NewForm.aspx");
        if( idxForm >= 0 ) {  //NewForm - Saving a new record
            window.opener.location.reload(); //Refresh calling page
            window.close();
        }
        var idxForm2 = location.pathname.indexOf("EditForm.aspx")
        if( idxForm2 >= 0 ) {  //EditForm - Saving an update to a existing record
            window.opener.location.reload(); //Refresh calling page
            history.go(-1);
            location.reload(true);
        }   
    });
   });
});

Actual Results: Either record saves with attachments and the user is directed to the SP Library AllItems.aspx OR user stays on the EditForm.aspx tab but the record is not updated with the added attachment.

Desired/Expected Results: Perform exactly like it does when the user Saves without adding attachments... The calling page is updated, the edit page is updated, and the user stays on the edit page. This needs to happen when the user adds attachments as well.


Solution

  • Ended up setting a session cookie on save event with the EditForm url and testing for it in AllItems.aspx, so if true it will redirect back to the specific edit record page.