rahman_akon18
rahman_akon18

Reputation: 346

Is there any condition to detect only when browser close (x) is pressed in javascript?

I am using beforeunload function which works fine but it fires also if i press any button or link in my page. what is the way to fire the event when only the close (x) button is pressed? My code:

window.addEventListener("beforeunload", function (e) {
    $.ajax({
        url: 'logout.php',
        type: 'POST',
        async: false,
        timeout: 4000
    });
});

Upvotes: 3

Views: 303

Answers (2)

spaniard
spaniard

Reputation: 560

It's not possible to differentiate 100% between close, refresh, form submission or link press. If you really need this, you can approximate a result based on:

  • The position of the cursor. If it's in right corner on Mozilla or Chrome it would mean that the X is pressed. Left right corner for Safari, etc.

  • Maybe add click events to all <a> html tags to set a FLAG to true.

  • Same than above to other similar tags like <form> or others which could redirect the user to other website.

  • Catch key press events to look for press of the key F5.

Even with all this, you can not be sure about it. If the use just closes the tab, or he click the reload button you could mistake, but at least gives you an approximation.

Upvotes: 3

Charlie
Charlie

Reputation: 23798

It is not possible to detect these actions as of early 2016.

Upvotes: 3

Related Questions