-1

Before marking this question as duplicate READ THIS QUESTION

I'm searching for a way that when a visiter leaves my webpage, he is redirected to another page. (He shouldn't close the page)

Some examples:

  1. I got the page open and I open another tab in my browser, then the person should be redirected to the other page, because he left the current "open" tab.
  2. When the person opens another program, the website isn't "active" anymore and it should redirect to another page.

I don't want an action when the user leaves the webpage, I want a reaction if he leaves it open but opens another program, another tab, etc.

Praveen Kumar Purushothaman
  • 164,888
  • 24
  • 203
  • 252
Thempower
  • 71
  • 1
  • 3
  • 12

1 Answers1

2

You can use the blur even on the window. When a window gets closed, it fires unload event. Attaching the code to these two events will work for you:

$('body').on('mouseleave', function () {
   $(window).on('beforeunload blur', function(){
      // User has left!
      // Sign out the user?
      // I really hope alert should not work here! It prevents it from closing.
   });
});

As per your comments, if you want to make sure they are not checking, you really need to use only the blur event, which gets triggered if the window is moved away. You should not use beforeunload that gets executed when the window is closed.

Alternatively, you can also invalidate the user if he presses the Ctrl and Alt keys, which are used for navigating out of the window. I have seen such kind of tests while taking my interview. But if I am gonna be a student, I will be hating such tests! :P

Still I can cheat it by using another devices like:

  • Mobile phone
  • Smartphone
  • Another Laptop / Desktop
Praveen Kumar Purushothaman
  • 164,888
  • 24
  • 203
  • 252
  • 1
    Give me a second gonna try it :) – Thempower Sep 19 '15 at 08:50
  • I'm using Google Chrome for the moment and I tried both only with blur and with both. If I open another tab it redirects: great! If I open another program on my taskbar it doesn't redirect. Is this impossible to detect? – Thempower Sep 19 '15 at 08:59
  • Check this one out .. http://stackoverflow.com/questions/1060008/is-there-a-way-to-detect-if-a-browser-window-is-not-currently-active – Asons Sep 19 '15 at 09:07
  • Exactly thanks a lot! I was searching with the wrong words... – Thempower Sep 19 '15 at 09:08