There are a couple of questions on StackOverflow about distinguishing download links in onbeforeunload
event handler, the usual use case being skipping loading animation. The simple solution is to use the download
attribute on the link itself, but this can’t be applied for forms. I had the same problem and fortunately I found a solution.
What I did was the obvious thing of checking the properties of the event object, passed to the handler. In Firefox there is explicitOriginalTarget
property and when the event is triggered by a form submission, the property is a reference to the submit button (if the form is submitted by pressing the button). In Chrome there is no such property, but there is another one that does the job – srcDocument.activeElement
. This also points to the submit button of the form. Internet Explorer on the other hand does not have any of these shortcuts, so I had to use the long reference event.currentTarget.document.activeElement
.
So what I did was add a data-download
attribute to the form and check for it in the onbeforeunload
handler like this:
window.onbeforeunload = function (e) { var target = e.currentTarget.document.activeElement; if ( target.form ) { target = target.form; } if ( ('getAttribute' in target) && (target.getAttribute('download') != undefined || target.getAttribute('data-download') != undefined) ) { return; } // Show loading spinner or do whatever you need to. };
The above code does two things – polyfill browsers that don’t support the download attribute and apply similar logic to forms. It works in IE 9, 10, 11 and Edge, latest Firefox and Chrome.
Етикети: javascript