2

I want to know how to execute some function when I close my browser... so the detail is I making website that going to sell items and the scenario is user login to my website and then they select some items that will put into shopping cart and when user closing browser then they account shopping cart will be empty, how to do that? I mean I already know how to clean the shopping cart but I don't know how to execute this function when closing browser

Felix Kling
  • 795,719
  • 175
  • 1,089
  • 1,143
PamanBeruang
  • 1,531
  • 5
  • 27
  • 64
  • possible duplicate of [Best way to detect when a user leaves a web page?](http://stackoverflow.com/questions/147636/best-way-to-detect-when-a-user-leaves-a-web-page) – Felix Kling Dec 21 '13 at 03:43

4 Answers4

1

Try

window.onbeforeunload = function(e){
//Do some thing here
};

Find more info here

Nouphal.M
  • 6,304
  • 1
  • 17
  • 28
  • 1
    This works but it will override any existing handlers. Consider using: window.addEventListener('beforeunload', function(event) { /* your code */ }); – Yusufali2205 Feb 05 '18 at 19:13
0

This is most likely a duplicated question. Please have a look at onbeforeunload Javascript event.

Reference:

Community
  • 1
  • 1
Henry Cho
  • 770
  • 2
  • 15
  • 33
0

You can use jquery unload for that: http://api.jquery.com/unload/

Jeff Renaud
  • 317
  • 1
  • 6
-1

This will add a new handler:

window.addEventListener('beforeunload', function(event) { 
/* your code */ 
});

If you use:

window.onbeforeunload = function(e){
//Do some thing here
};

This will override any existing handlers and replace it with your own.

Yusufali2205
  • 1,222
  • 9
  • 17