0

I wanna alert the message. Example 1 is working but Example 2 isn't. Everything else like localStorage.setItem or console.log aren't working in Example 2 too. Why?

Example 1

$(document).on('unload', alert('Reloaded!'))

Example 2

$(document).on('unload', function (){
  alert('Reloaded!');
});
grevvx4
  • 15
  • 4
  • 3
    In the first example, you are not actually passing any callback to the event listener. You're executing the `alert` function, and passing its result (`undefined`) to the event listener. The second one isn't working because thankfully, some browsers [block `alert` on unload](https://stackoverflow.com/a/9386675/1913729) – blex Jan 04 '20 at 20:18
  • @blex that's the funny thing because even without the callback it is working BUT example 2 is not.. – grevvx4 Jan 04 '20 at 20:20
  • @blex maybe they block alerts, but do they block `localStorage.setItem` and `console.log` too? Because they are not working – grevvx4 Jan 04 '20 at 20:21
  • Maybe try `$(window).on('unload', /* ... */ )` ([JSFiddle example](https://jsfiddle.net/0eya1L7n/)) – blex Jan 04 '20 at 20:23
  • Not working too. `localStorage.setItem` and `console.log` work but alert is not working. But thanks for the answer – grevvx4 Jan 04 '20 at 20:28
  • Does this answer your question? [window.onunload is not working properly in Chrome browser. Can any one help me?](https://stackoverflow.com/questions/7794301/window-onunload-is-not-working-properly-in-chrome-browser-can-any-one-help-me) – Jb31 Jan 04 '20 at 21:12

0 Answers0