0

I want to fire the onbeforeunload event only when the tab or browser is closed and not upon refresh, link click and so on. I found a site where that works: https://checkout.deindeal.ch/

Steps to fire the event in Chrome:

  1. Put something into the cart
  2. Click on "Zur Kasse"
  3. Close tab
  4. onbeforeunload Message is shown and a popup opens. onbeforeunload events like refresh will not fire. I debugged their code, but could not find the place where they exclude those events or whatsoever.

Anyone out there who can find the correct place in the code?

Thanks!

user4095519
  • 271
  • 1
  • 5
  • 12
  • 1
    In a post from 2012, though the question is about IE8, [Antyrat's answer](http://stackoverflow.com/a/10637604/1169519) stands for all browsers, even today. – Teemu Oct 14 '14 at 16:27
  • I added something to the cart (I think, it's not in English) and closing the tab did nothing. No `onbeforeunload` was triggered. Chrome Version 37.0.2062.124 m on Windows 7 x64. – gen_Eric Oct 14 '14 at 16:31

1 Answers1

2

For readers that want to use onbeforeunload,

The event onbeforeunload should be used for preventing user's data loss, like filled in forms and other data that are not saved and will be lost upon page refresh.

Using onbeforeunload to prevent a user from leaving your page is annoying and will not stop the user from leaving.


You can not detect a browser tab refresh button press, unless the user use a shortcut that you can detect with key press (like Ctrl+F5). More info here : javascript beforeunload detect refresh versus close


Old answer was removed in order not to mislead anyone (it was not working on nowadays browsers).

More stack overflow links related on onbeforeunload use:

How can i get the destination url in javascript onbeforeunload event?

How to prevent calling onbeforeunload when page refresh

Fire onbeforeunload confirm alert for external sites only

GramThanos
  • 3,572
  • 1
  • 22
  • 34
  • Thanks, how would that help in my case? When I close the browser window, the goto var still contains my domain ... did I miss something? – user4095519 Oct 15 '14 at 06:38
  • `new URL(e.target.URL).hostname` doesn't work for me: `JavaScript runtime error: Object doesn't support this action`. IE11. – Csaba Toth Jul 19 '15 at 05:14
  • IE do not support URL object. You can get the host url by checking if a e.target.href exist and parsing it. – GramThanos Jul 19 '15 at 20:15