Detect browser close / page exit using Javascript
Here is a sample code to detect that a browser is closed or a link has been clicked. This detects if the user is exiting the page. I am using this for locking/unlocking table rows in my database.
<script type="text/javascript">
function myUnloadEvent() {
alert (`call ajax to update stuff`);
}
</script>
<body onUnload = " myUnloadEvent(); " >
Body of the page here.
</body>The onUnload() event is responsible for the entire thing.
Browse Timeline
Comments ( 4 )
Hi! I was surfing and found your blog post… nice! I love your blog. :) Cheers! Sandra. R.
I love your site. :) Love design!!! I just came across your blog and wanted to say that I
I want to display an alert when user closes the web browser. onLoad , onBeforeUnload are get triggered when user refresh the page or try to go to another page. What I really want to track is user closing the window by pressing (X) or Cntrl+W. I’m using JSF and XHTML and it’s a SEAM environment. Should work for FF and IE. Do you have any idea?
Sanjeewa, the example above should work. It will call the myUnloadEvent() when the window/tab is closed. Either by clicking on the X-button or pressing CTRL+W. This should also work in IE and FF.


