0

Here is My code : but it redirect on both click stay on page and leave page . I need to redirect user on specific URL click on leave page .

<script>
var stayonthis = true;
  var a;
  function load() {
   window.onbeforeunload = function(e) {
        if(stayonthis){
         a = setTimeout('window.location.href="http://google.com";',100);
         stayonthis = false; 

         return "Do you really want to leave now?";
        }
        else {

            clearTimeout(a);
        }

    };
  }
  window.onload = load;
</script>
AMBIKAST
  • 3
  • 2
  • `stayonthis` is always `true` before the `if` test. – A.L Jan 30 '15 at 12:30
  • you could check via location.href where an user is right now. – Blauharley Jan 30 '15 at 12:30
  • 1
    So options are: you stay here or you go where I'll send you? That's like hijacking the user, don't you think? – ffflabs Jan 30 '15 at 12:38
  • @amenadiel yes i need to send user to another url when click on leave page . – AMBIKAST Jan 30 '15 at 12:41
  • So if the user is in your site, and wants to go back to google you instead send him to another place... believe me, people will hate when that happens. – ffflabs Jan 30 '15 at 12:42
  • @amenadiel: No, you don't *need* to. And you really, really, really shouldn't. If someone (client, boss) is telling you to do that, tell them A) Why you can't (browsers won't let you), and B) Why it's wildly inappropriate. – T.J. Crowder Jan 30 '15 at 12:44
  • Bottomline is: you can't override the onbeforeunload dialog, and you can't redirect the user. There's a [very good answer here](http://stackoverflow.com/questions/6063522/dialog-box-runs-for-1-sec-and-disappears/6065085#6065085). What you can do is spawn another tab with your promotional content. But it's still very frustrating to the user. – ffflabs Jan 30 '15 at 12:57
  • User will not frustrated from this because redirect url is related to their benefits . it is only to show some important thing for next week on current url. i made some concept on this – AMBIKAST Jan 30 '15 at 13:01
  • Sorry, but I don't buy it. If it's information they need to see, it should be on the page they're looking at or linked from it. *Pushing* another page at them when they're leaving is simply not appropriate. – T.J. Crowder Jan 30 '15 at 15:00

1 Answers1

3

You cannot force the user to a new page when leaving yours, nor should you. People used to do it, and so browser vendors have gotten really good at preventing it.

Instead, provide your users useful content on your page and a link to the other page if you think they'll want it. If you don't think they'll want it, don't try to force it on them.

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875