Search code examples
javascriptangularwindow.openonbeforeunload

Window.open is firing beforeunload


When I call

window.open("aPageInMyApp","MsgWindow")

My EventListener is firing, sometimes, and sometimes it is not.

@HostListener('window:beforeunload') logout(){//some code}


Solution

  • The reason for this, is if you are calling

    window.open("aPageInMyApp","MsgWindow")
    

    From inside the window that you opened, the window.name will be the same. This will cause the browser to attempt to refresh that tab. Which will then fire off the beforeunload. To prevent this instead of using "MsgWindow" use something dynamic that won't repeat to ensure the name of the window is never the same. Use a solution like A typescript Guid class? to generate something on the fly.

    window.open("aPageInMyApp", Guid.newGuid())
    

    This will ensure you never attempt to open the same window within the same window.