2

I'm trying to warn the user before reloading or closing the page, but the problem is that it works on reloading page but not on closing the page.

Here is the Javascript code I'm using :

window.onbeforeunload = function(e) {
  var dialogText = 'Dialog text here';
  e.returnValue = dialogText;
  return dialogText;
};

This works when reloading the page but it does not work when closing the page I've even tried :

window.onunload = function(e) {
  var dialogText = 'Dialog text here';
  e.returnValue = dialogText;
  return dialogText;
};

And

window.addEventListener('unload', myFunc, false);

But does not work either. Thanks to everyone for helping.

  • @AlexandreMiziara I'm using it already and it works only when reloading the page but when closing it nothing happens – Rahmani Seif El Moulouk Apr 13 '18 at 14:02
  • 1
    @RahmaniSaif Your `window.onbeforeunload` example works fine in latest Chrome and IE11. What Browser are you using? – Nope Apr 13 '18 at 14:05
  • @Nope Chrome 65.0.3325.181 – Rahmani Seif El Moulouk Apr 13 '18 at 14:07
  • @RahmaniSaif hmm, I'm testing this in jsfiddle on Chrome version 65.0.3325.181 and it shows a warning on page reload and when trying to close the tab. The fiddle also works in IE11 https://jsfiddle.net/qy4z8c8a/ – Nope Apr 13 '18 at 14:10
  • I got nothing when closing the window – Rahmani Seif El Moulouk Apr 13 '18 at 14:13
  • Not sure what to tell you. Ones the fiddle runs, clicking "Run", clicking page reload or closing the tab triggers the alert :/ Sorry. – Nope Apr 13 '18 at 14:14
  • 1
    Custom dialogs are deprecated as explained [here](https://stackoverflow.com/a/276739/9436122) – Alexandre Miziara Apr 13 '18 at 14:14
  • @AlexandreMiziara I think OP is having issue with alert not showing up at all when closing the window, never mind the message, though off course that is also true but doesn't seem to be OPs issue going by the comments. – Nope Apr 13 '18 at 14:15
  • @AlexandreMiziara What I'm trying to do is I'm calculating how much time the user spent on a page, and what I'm trying to achieve is send an ajax request to my server once the user leaves the page to store the time he spend on that page, and this is the reason I need it to work on reloading and closing the page – Rahmani Seif El Moulouk Apr 13 '18 at 14:31
  • @RahmaniSaif what exactly not works? The dialog is not shown or your callback function to send a post to your api is not executed? You should provide more details – Alexandre Miziara Apr 13 '18 at 14:49
  • It works fine when reloading the page but it does not work when closing the window – Rahmani Seif El Moulouk Apr 13 '18 at 14:53

0 Answers0