0

I want to show alerts for the following events:

  1. Page onLoad
  2. Page Refresh
  3. Before Close
Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
  • I am sure there are dupes on this, but there is NO way to know what it is doing. – epascarello Jan 11 '17 at 13:28
  • 1
    possible dupe http://stackoverflow.com/questions/3888902/javascript-detect-browser-close-tab-close-browser – blckt Jan 11 '17 at 14:27
  • kindly accept an answer if they solve your problem. Otherwise be sure to comment and explain what you are searching for with more detail. :) – Penguin9 Jan 12 '17 at 16:51
  • Currently I develop disable multi login user. As per client requirement when tab close or browser close that time user logout automatically. for that I have find out javascript event using I call ajax and clear database session id – RK Infotech Jan 13 '17 at 04:17
  • That would be `onunload` > function logout(), Sir. :P – Penguin9 Jan 13 '17 at 19:22
  • @RaisingAgent onunload event trigger when page refresh also. That's issue when using onunload and onbeforeunload event – RK Infotech Jan 16 '17 at 05:11

2 Answers2

2

Use alert for load , and return statement for unload and refresh

below the used code .

// 1-Page Load
window.onload = function() {
  alert("Page loaded");
  
  //disable unload message when clicking on links (<a>)
  var links = document.getElementsByTagName("a");
  for (var i = 0; i < links.length ; i++) {
    links[i].addEventListener("click",function(){
    window.onbeforeunload = null;
    })
  }
}

// 2-Page Refresh or  3-Before Close 
window.onbeforeunload = function() {
  return "Page unloaded !";
}
<a href="#">link</a>
Bourbia Brahim
  • 14,459
  • 4
  • 39
  • 52
  • I have a feeling the OP already knows about these events and wants to know how to determine the difference between refreshing the page and closing it, which is impossible. – somethinghere Jan 11 '17 at 17:06
  • It is possible actually^, but the tab will still be closed – Penguin9 Jan 12 '17 at 16:52
1

Add this to your <head> tag, you can pick between onbeforeunload and onunload, which ever you prefer. Although onunload also gets triggered, when you close the tab / browser.
The window.alert triggers, when the page is loaded.

This is it:

<script type="text/javascript">
  window.alert("alert!");
  
  window.onunload = function (){
      alert("onunload alert");
  };
  window.onbeforeunload = function (){
      alert("onbeforeunload alert");
  };
</script>
Penguin9
  • 481
  • 13
  • 23