Search code examples
javascriptpopuponbeforeunload

javascript open popup before closing the current tab


I want to open a popup when the user closes the last tab of the current site. The problems I have is that

  • when the browser prompts the user (onbeforeunload returning a non null value), then the popup is blocked by the browser (see case 1 below)
  • when the browser does not prompt anything to the user (onbeforeunload not returning anything), then the popup is not opened at all and seemed to be totally ignored by the browser (why is that?) (see case 2 below)

Case 1: prompt and popup blocked (code from this answer)

window.onbeforeunload = function (e) {
    e = e || window.event;

    window.open('http://localhost', '_blank');

    // For IE and Firefox prior to version 4
    if (e) {
        e.returnValue = 'Sure?';
    }

    // For Safari
    return 'Sure?';
};

Case 2: no prompt, no popup, page closing "normally"

window.onbeforeunload = function (e) {
    e = e || window.event;

    window.open('http://localhost', '_blank');
};

Solution

  • From the specification:

    An algorithm is allowed to show a popup if any of the following conditions is true

    The task in which the algorithm is running is currently processing an activation behavior whose click event was trusted.

    The window closing is not a click event.

    The task in which the algorithm is running is currently running the event listener for a trusted event whose type is in the following list:

    unload is not in that list.

    The task in which the algorithm is running was queued by an algorithm that was allowed to show a popup, and the chain of such algorithms started within a user-agent defined timeframe.

    For example, if a user clicked a button, it might be acceptable for a popup to result from that after 4 seconds, but it would likely not be acceptable for a popup to result from that after 4 hours.

    Again, no. The task wasn't queued.

    It is not possible to open a popup in response to a user trying to leave your site. It would enable too many harmful behaviours (click on this advert, quit, popup, you must click on this advert, loop).