Custom closing operation on javascript [duplicate]

Hi i’m using the following script to itercept the closing event in javascript:

window.addEventListener('beforeunload', function(e) {           
        e.preventDefault();
        e.returnValue = '';         
    });

But it intercept all the event that make the program leaving the page. I want to perform this operation only on closing call(like tab/browser closing) but not in the program function (I.E. login/logout). There is a way to perform this?
Is also possible to gain the response of the user to the popup message?
Thanks