Thomas Lee
Thomas Lee

Reputation: 83

How to capture the browser window close event on PHP?

I found the code below in stackoverflow and it works fine, but how can I capture <input type="button">?

I tried $('input').on('click'), $('input.button').on('click'), and $('button').on('click') also didn't work. Also is there any method to capture refresh event? Many thanks.

var inFormOrLink;
$('a').on('click', function() { inFormOrLink = true; });
$('form').on('submit', function() { inFormOrLink = true; });

$(window).on("beforeunload", function() { 
    return inFormOrLink ? "Do you really want to close?" : null; 
})

Upvotes: 2

Views: 2991

Answers (2)

saraman
saraman

Reputation: 566

If I get you correctly, you want to know when a tab/window is effectively closed. Well, AFAIK the only way in Javascript to detect that kind of stuffs are onunload & onbeforeunload events.

Unfortunately (or fortunately?), those events are also fired when you leave a site over a link or your browsers back button. So this is the best answer I can give, I don't think you can natively detect a pure close in Javascript. Correct me if I'm wrong here.

Upvotes: 0

Kremnev Sergey
Kremnev Sergey

Reputation: 332

To capture click on the <input type="button"> you can do

$('input[type=button]').on('click', function() {});

To capture refresh event you can do

window.onbeforeunload = function(e) {};

To capture refresh event with jQuery you can use unload

$(window).unload(function() {});

Upvotes: 2

Related Questions