How to logout during onbeforeunload/onunload using Javascript

China☆狼群 提交于 2020-04-28 19:57:51

问题


<script type="text/javascript">

window.onbeforeunload=before;
window.onunload=after;

function before(evt)
{
   var message="If you continue, your session will be logged out!";
   if(typeof evt=="undefined"){
      evt=window.event;
   }
   if(evt){
      evt.returnValue=message;
   }
}

function after()
{
   var flex=document.${application}||window.${application};
   flex.unloadMethod(); //calls the flex class containing the "unloadMethod()" which
                        //calls the logout.jsp that does the actually dropping of credentials
}

</script>

So this is my thought: When the user clicks back, refresh, or closes the window, the standard onbeforeunload pop-up box will appear along with the text located in my message variable. Then, if the user hits Cancel, the onunload event won't be executed and the user will stay on the current page. But if the user hits Okay, then the onunload event should fire off, which then executes my logoff classes.

This is what's happening: The pop-up appears when needed and the Cancel button also works. But if the user clicks Okay, it seems like the onunload event fires off too quickly for my logoff classes to execute, because it never logs them off.

I know that my logout classes work because if I just call my flex.unloadMethod in the onbeforeunload, it logs them off.

I've researched this for a week now and it seems that I'm close but I'm putting something in the wrong place. If you have any examples or advice, it would be appreciated.


回答1:


So, I've figured out some issues with my question with the help of Sunil D. The onunload event fires too quickly for my event to be triggered, so I've decided not to include a warning message, but just log the user off all together using the onbeforeunload event:

<script type="text/javascript">

window.onbeforeunload=before;
window.onunload=after;

function before(evt)
{
   var flex=document.${application}||window.${application};
   flex.unloadMethod(); //calls the flex class containing the "unloadMethod()" which
                        //calls the logout.jsp that does the actually dropping of credentials
}

function after(evt)
{

}

</script>


来源:https://stackoverflow.com/questions/16610950/how-to-logout-during-onbeforeunload-onunload-using-javascript

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