Unexpected performace.navigation.type onbeforeunload

五迷三道 提交于 2019-12-09 22:20:01

问题


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?


回答1:


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.



来源:https://stackoverflow.com/questions/35468281/unexpected-performace-navigation-type-onbeforeunload

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!