Den
Den

Reputation: 379

Show popup window when the browser close

I'm developing an eCommerce(PHP) web site and here's my requirement.

Once the customer leave the order page or close the browser, I would like to offer another product with pop up or alert box. If they choose 'Yes', it will redirect to another product page instead of closing window.

I tried with javascript window.open() on body "onunload" event. But the browsers keep blocking it.

Is there anyway to accomplish this?

Thank you, Den

Upvotes: 4

Views: 5788

Answers (2)

Brian
Brian

Reputation: 529

First off: This is not user friendly at all. Just like @Dagon said, nobody want's to be restricted from leaving a page and then shown a spam of different items being sold. With that being said, I'm sure you have a legit reason, or rather are being told to do this. So here is my answer---

There is no way to do this with the onunload event. Once that event is being fired, there is no chance to redirect or cancel the unload because it is literally on the unload event.

Your best chance to do this will be in the onbeforeunload event. This is the only event that actually pauses the onunload event and can also cancel the onunload from executing. The onbeforeunload event has two different outcomes

  • If you return something in the onbeforeunload event, then a default dialog box will appear, with your text inside, when the user tries to navigate away. The user can hit OK or Cancel. If they hit OK, the browser continues to navigate away. If the user hits Cancel, the onunload event is, you guessed it, cancelled. Surprisingly, this seems to be the only way to cancel the onunload event without anchoring.
  • If you don't return anything, your code that is inside the onbeforeunload event will fire without the user knowing. (This code has to be relatively short because the onbeforeunload event doesn't allow much time.

An idea you might want to try (I've never attempted this) is try adding a hyperlink into the return statement of the onbeforeunload event. Again, no idea if this will work.

Below is a very simple sample of the onbeforeunload and onunload events:

<script type="text/javascript"> //may not be neccesary for your code

window.onbeforeunload=before;
window.onunload=after;

function before(evt)
{
   return "This will appear in the dialog box allong with some other default text";
   //If the return statement was not here, other code could be executed silently (with no pop-up)
}

function after(evt)
{
   //This event fires too fast for the application to execute before the browser unloads
}

</script>

I know you want to create an alert or a confirm pop-up but that has some issues too. The typical programmer does not have access to the source-code of the onbeforeunload and onunload events, so no one is 100% sure of everything they do. What I know, from my testing, is that it seems impossible to have a custom pop-up appear only once and also execute other code.

If the user is closing the webpage the only way to capture that is in the onbeforeunload event. There's no way out of that one. If the user uses the back button, the onbeforeunload event is also fired there. I know what your end goal is, but I have a suggestion, if allowable of course. Try anchoring links or buttons on your page. If it is absolutely neccesary to have this pop-up, the only sure-fire way of doing this would be to anchor the pop-up to links/buttons that are on your webpage. But of course this would only work if they are trying to navigate away using your links (which would be a little more user-friendly) but if they try to navigate away using external links (like favorite links or closing the browser) then it would not be executed.

Best of luck in your endeavours. Onbeforeunload and onunload are tricky.

Upvotes: 2

JamesN
JamesN

Reputation: 387

Same same in my portal, When user close the browser I need some time to postpone for resetting some data. The code I use below, It work for me. When user close browse ,tab or try to redirect to another page, a message will display for user to choose stay or leave.

var validNavigation = false;

function wireUpEvents() {

  var dont_confirm_leave = 0; //set dont_confirm_leave to 1 when you want the user to be able to leave withou confirmation
  var leave_message = cmsLeaveMessage;
  function goodbye(e) {
    validNavigation = isUserLoggedIn == 0 ? true :  validNavigation;
    if (!validNavigation) {
      if (dont_confirm_leave!==1) {
        if(!e) e = window.event;
        //e.cancelBubble is supported by IE - this will kill the bubbling process.
        e.cancelBubble = true;
        e.returnValue = leave_message;
        //e.stopPropagation works in Firefox.
        /*
        if (e.stopPropagation) {
          e.stopPropagation();
          e.preventDefault();
        }
        */
        //return works for Chrome and Safari
        $.ajax({
            url: linkResetTask,
            type: 'POST',
            dataType: "html",
            success:function(){
                init("Employee");
            }
        });
        validNavigation = false;
        return leave_message;
      }
    }else
    {
        validNavigation = false;
    }
  }

  $(window).bind('beforeunload', goodbye );


  // Attach the event keypress to exclude the F5 refresh

    $(document).bind('keydown keyup', function(e) {
        if(e.which === 116) {
           validNavigation = true;

        }
        if(e.which === 82 && e.ctrlKey) {
           validNavigation = true;

        }
    }); 

}

// Wire up the events as soon as the DOM tree is ready
$(document).ready(function() {
  wireUpEvents();
});

Upvotes: 0

Related Questions