开发者

How to handle browser close (cross) in javascript or Jquery

I need to handle browser close (through cross on the top right side) through javascript or Jquery. I have found lots of forums or blog where they give a solution to do this using onUnload or OnbeforeUnload etc. But these event always get triggered whenever page refresh or go back and forward in browser. I need to expire cookies only when user signout from application or user clos开发者_StackOverflow中文版e the window. If i use the onUnload or OnbeforeUnload event they get triggered even when page refreshed or back or forward as i have already told.

Any help really appreciated. Thanks


Non persistent cookies is one workaround. second, you can do some small things before the customer closes the tab. javascript detect browser close tab/close browser but if your list of actions are big and the tab closes before it is finished you are helpless. You can try it but with my experience donot depend on it.

window.addEventListener("beforeunload", function (e) {
  var confirmationMessage = "\o/";
  /* Do you small action code here */
  (e || window.event).returnValue = confirmationMessage; //Gecko + IE
  return confirmationMessage;                            //Webkit, Safari, Chrome
});

https://developer.mozilla.org/en-US/docs/Web/Reference/Events/beforeunload?redirectlocale=en-US&redirectslug=DOM/Mozilla_event_reference/beforeunload


OnbeforeUnload can be used for this purpose with some work around. I think you can use a flag value something like wasClose=true/false , which should be made to false when user is clicking on any elements(can be applied for a div/body if it can receive the bubble). The better you can get some js library from web and use.

Else, we will need to manually monitor right clicks, click targets(if inside body) etc.. and decide, the window.close() or a click on close is the event caused the Onbeforeunload() call.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜