Search code examples
javascriptaddeventlisteneronbeforeunload

beforeunload doesn't work when binding to event listener


need help with beforeunload event. I was trying to add a event listener for 'beforeunload' to my page like this window.addEventListener('beforeunload', log.Flush()); and it doesn't go through the flush() function when I click on a link to navigate away from the page.

Although, when I set the

window.onbeforeunload = function () {
                return log.Flush();
            };

debugger goes through the Flush() function. Any hint why? Is there a better standard way to set a function to be called when beforeunload?

Thanks in advance


Solution

  • This is because you're invoking your function in place of subscription, instead of this try to just reference to your function.

    window.addEventListener('beforeunload', log.Flush);