1

A pop up is opened when a user clicks a button. This pop up will go to a holding page, and wait for the user to leave the website or close the browser.

Then when the user leaves or closes the browser, it will redirect the pop up location to a different site.

I have tried several variants of the following code:

win=window.open('google.com','popup'); //just to illustrate the "win" = my window.open().

$(window).bind('beforeunload', function() {
   window.win.location.href="http://the-new-location.com";
   //tried something like this as well:
   //win.location.href="http://the-new-location.com";
});

But without luck. I am not brilliant with javascript /jquery so any help on how to make this work would be deeply appreciated.

Thanks!

MrE
  • 1,124
  • 3
  • 14
  • 28
  • What happens if someone closes the popup before they leave the page? By the way your code works, but it relies on the user having very relaxed settings on their popup blocker. – Rory McCrossan Apr 10 '12 at 12:47
  • Nothing. It should take them to a survey but if they choose to close it before they leave then nothing further should happen when they leave the site. – MrE Apr 10 '12 at 12:50
  • Hmm ok. I tried in chrome, and it won't seem to work for me. the popup will only appear if the users click a button to open it. so it shouldn't be blocked. – MrE Apr 10 '12 at 12:51
  • Ok, it seems like it is because the "beforeunload" won't fire, even in pure javascript. – MrE Apr 10 '12 at 12:58

2 Answers2

2

I found a solution:

win=window.open('google.com','popup');

window.onunload = redirect;
function redirect(){
   window.win.location.href="http://the-new-url.com";
};
MrE
  • 1,124
  • 3
  • 14
  • 28
1

I know you already have a prototype working, but if you want the jquery option:

var popup = window.open('http://google.com', 'popup');

$(window).unload(function() {
    if(!popup.closed) {
        popup.location.href = 'http://surveyurl.com/';
    }
});

You should also be checking to see if popup.closed is there.

Jordan
  • 31,971
  • 6
  • 56
  • 67