Search code examples
javascriptcross-browseronbeforeunload

Unexpected performace.navigation.type onbeforeunload


I'm trying to handle some logic on before unload and I don't want that logic to run if the user is reloading the page or going back.

I've set up something like this.

window.onbeforeunload = function(e) {
  if(window.event && window.event.clientX){ //IE
    //some logic
  } else if (e.currentTarget.performance.navigation.type === e.currentTarget.performance.navigation.TYPE_RELOAD) {
     // another logic
  } else if(e.currentTarget.performance.navigation.type === e.currentTarget.performance.navigation.TYPE_BACK_FORWARD){
     // yet another logic
  }
}

I have other code to handle refresh and such from keyboard input that all seems to be working ok. Right now I'm concerned with this piece of code. For some reason on the first reload or back button the navigation.type comes back as 0, but after that all other reloads or back buttons populate the correct value in navigation.type. Even in IE on the first reload something is not being set correctly (not sure if its the mouse location or what yet). What could be causing something like this?


Solution

  • First of all, I think what you wanted to write was e.currentTarget.performance.navigation.type (not e.current.performance.navigation.type), which is the same as writing window.performance.navigation.type. This variable tells you how this page was navigated to, not the type of navigation that the page is exiting through.

    Why you get performance.navigation.type as 0 (performance.navigation.TYPE_NAVIGATE) the first time is that the page was loaded by direct navigation that first time. Subsequent reloads will set performance.navigation.type to 1 (performance.navigation.TYPE_RELOAD) because the page is now loaded by reloading. So, you are getting the method that was used to load the page, not the method that the user is using to exit the page.