-4

When user is trying to close browser tab I need to ask him question if he wants to fill in survey. If he wants to, it should redirect him to google form and if he don`t want to, it should just close tab.

I tried window.onbeforeunload but confirmation window raises on every click on page buttons but I need it to be triggered only when trying to close tab.

Are there any suggestions?

tetiross
  • 192
  • 3
  • 17
  • @8protons I tried `window.onbeforeunload` but confirmation window raises on every click on page buttons – tetiross May 11 '16 at 14:38
  • possible duplicate of http://stackoverflow.com/questions/1408922/javascript-can-i-redirect-user-in-onbeforeunload-if-cant-how-to – Regis Portalez May 11 '16 at 14:39
  • There is no event specific for closing tab/window. The best you could get is [that](http://stackoverflow.com/questions/18932464/javascript-onbeforeunload-disable-for-links/18932521#18932521) and [this](http://stackoverflow.com/questions/16695886/using-onbeforeunload-event-url-change-on-selecting-stay-on-this-page/16824414#16824414) – A. Wolff May 11 '16 at 14:50

2 Answers2

1

The beforeunload event fires whenever the user leaves your page for any reason.

jQuery(window).bind(
    "beforeunload", 
    function() { 
        return confirm("Do you really want to close?") 
    }
)
Sergi Case
  • 226
  • 2
  • 12
  • `beforeunload` triggers anytime user clicks on page buttons, but I need it to be triggered only if trying to close tab. – tetiross May 11 '16 at 14:47
1

I'm assuming what you want to do is show some sort of pop up when the user indicates intent to leave.

This can be achieved by using the javascript 'mouseout' event. I.e. if the mouse leaves the browser window (say user goes to close a tab, the window, or click on another tab, etc.) then your survey is fired.

Obviously doesn't always work - the user might be trying for example to click on a browser menu item in which case your survey would be fired. Also I do not believe it would work on touch devices.

But if you can live with those types of kinks, here's the code you need.

// Set up an event listener to capture exit intent
function addEvent(obj, evt, fn) {
    if (obj.addEventListener) {
        obj.addEventListener(evt, fn, false);
    }
    else if (obj.attachEvent) {
        obj.attachEvent("on" + evt, fn);
    }
}

// Trigger exit intent on mouseout event
addEvent(document, 'mouseout', function(evt) {
    if (evt.toElement == null && evt.relatedTarget == null ) {
        console.log('Let's do some magic here');
    };
});
dot-punto-dot
  • 261
  • 4
  • 17