0

I wanna exploit a special case when user leaves a page. I create a method to do something when user leaves a page. But, if user is staying on this page, and clicks a link to open new page in new tab. So, does user leave page?

Can you tell me a hint? Thank you!

p/s: I'm using MVC 5 and I can use jQuery/javascript.

  • @vinayakj No. I want to clear all temporary data if user leaves `this page` truly. But, if user opens other page in new tab, the temporary data won't be cleared. –  Jun 28 '15 at 19:28
  • Does "leaves this page" mean when the user _closes_ the tab? – Ram Jun 28 '15 at 19:29
  • save the the data in `localStorage`, whenever page loads get the data from `localStorage` and store it in some local variable, and on `onbeforeunload` clear it – vinayakj Jun 28 '15 at 19:32
  • @Vohuman Yes. `leaves this page` means user `closes` this page or clicks `back` button. But if user opens a page in new tab, that doesn't mean `leaves this page`. Because he doesn't `closes` the page or clicks `back` button. –  Jun 28 '15 at 19:32
  • If this is the case the question is duplicate of [this question](http://stackoverflow.com/questions/3888902/javascript-detect-browser-close-tab-close-browser). I'll reopen the question. – Ram Jun 28 '15 at 19:33
  • Using 'onunload' event, details in this answer: http://stackoverflow.com/questions/147636/best-way-to-detect-when-a-user-leaves-a-web-page?answertab=votes#tab-top – Huy Aug 13 '15 at 08:14

1 Answers1

0

You can't detect opening a new window or tab, but you can listen for the 'onunload' event.

jQuery(window).bind("unload", function() {
    //your code here
});

This should fire when clicking on a link, closing the tab/window or pressing the back button.

Josh Stevens
  • 3,943
  • 1
  • 15
  • 22