Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Distinguish onbeforeunload for File Download vs Page Change

I have an onbeforeunload event that's supposed to get triggered any time a user goes to a new page. It works well enough, but I've found that it also gets triggered in Chrome any time a user downloads a file from the page they're on.

I'd like to be able to tell if the event is getting fired because it's being triggered by a file download. What's the best way to do that?

EDIT: As a clarification, I don't own the site that I'm listening to onbeforeunload on. The event is listened to by a Javascript snippet that's being installed on 3rd party sites.

like image 372
dshipper Avatar asked Jan 18 '13 02:01

dshipper


People also ask

What is the difference between Onbeforeunload and Onunload?

onbeforeunload Below are my findings on the iPad; Using window. onunload , I am able to get an alert when user navigates to a different page from myPage. html (either by clicking on some link or doing a Google search while on myPage.

What triggers Onbeforeunload?

The onbeforeunload event occurs when the document is about to be unloaded. This event allows you to display a message in a confirmation dialog box to inform the user whether he/she wants to stay or leave the current page. The default message that appears in the confirmation box, is different in different browsers.

What does window Onbeforeunload do?

The beforeunload event is fired when the window, the document and its resources are about to be unloaded. The document is still visible and the event is still cancelable at this point. This event enables a web page to trigger a confirmation dialog asking the user if they really want to leave the page.

What does Onunload do in JavaScript?

The onunload attribute fires once a page has unloaded (or the browser window has been closed). onunload occurs when the user navigates away from the page (by clicking on a link, submitting a form, closing the browser window, etc.)


1 Answers

If you add download="[FILENAME]" to the a tag, it seems to prevent onbeforeunload from firing:

<a download="myfile.jpg" href="mysite.com">click me</a> 

This is a much simpler solution. You can leave off the filename and just say 'download' to use the default filename. Let me point out this has the side effect of forcing redownload instead of using cache. I think this was added to chrome and ff in 2012. Not sure about safari or ie support.

like image 125
jsarma Avatar answered Sep 22 '22 15:09

jsarma