Shaitender Singh
Shaitender Singh

Reputation: 2207

Open a custom dialog on browser window/tab close

I am trying to add a survey confirmation box with Ok/Cancel on browser window/tab close. I need to redirect user to survey link on Ok button click.

Trying to implement the same with below code.

var leave_message = 'Wait! Would you like to respond to a quick Survey?'

function bye(e) {
    if (!e) e = window.event;   
    e.cancelBubble = true;

    if (e.stopPropagation) {
        e.stopPropagation();
        e.preventDefault();
    }
    e.returnValue = leave_message;

    if (confirm(leave_message)) {
        window.open("www.surveylink.com");
    }
}

window.onbeforeunload = bye;

Please suggest above code is not working.

Upvotes: 0

Views: 4042

Answers (2)

Lazzaro
Lazzaro

Reputation: 189

onbeforeunload is not a regular event. A dialog asking you to stay on the page is casted if you return a string in the onbeforeunload event handler. If the user clicks on the "Stay on page" button in that dialog, unloading of the page is aborted. (More details at, for example, https://developer.mozilla.org/en-US/docs/Web/API/Window.onbeforeunload)

My approach to that problem would be to set a variable that indicates that the page began unloading and then checking that variable regularly to determine if the unloading was aborted:

(function () {
    var triedToUnload = false;
    window.onbeforeunload = function (e) {
        triedToUnload = true;
        return "Wait! Would you like to respond to a quick Survey?";
    };
    window.setInterval(function () {
        if (triedToUnload) {
            window.open("www.surveylink.com");
        }
    }, 500);
}());

Upvotes: 1

Pratik Joshi
Pratik Joshi

Reputation: 11693

Use this to force your users to your site ,This is what you can do Most anything other than that is not possible.

$(window).bind('beforeunload', function() {
                      window.open("http://www.surveylink.com");
      return 'Do you really want to leave?' ;
});

Upvotes: 1

Related Questions