Identifying Between Refresh And Close Browser Acti

2019-01-01 07:10发布

When we refresh the page (F5, or icon in browser), it will first trigger ONUNLOAD event. When we close the browser (X on right top icon),It will trigger ONUNLOAD event. Now when ONUNLOAD event is triggered, there is no way to distinguish between refresh the page or close the browser. If you have any solution then give me.

9条回答
深知你不懂我心
2楼-- · 2019-01-01 07:51
    $(window).bind('unload', function () {
        if (/Firefox[\/\s](\d+)/.test(navigator.userAgent) && new Number(RegExp.$1) >= 4) {
            console.log('firefox delete');
            var data = { async: false };
            endSession(data);
            return null;
        }
        else {
            console.log('NON-firefox delete');
            var data = { async: true };
            endSession(data);
            return null;
        }
    });

    function endSession(data) {
        var id = 0

        if (window) { // closeed
            id=1
        }

        $.ajax({
            url: '/api/commonAPI/'+id+'?Action=ForceEndSession',
            type: "get",
            data: {},
            async: data.async,
            success: function () {
                console.log('Forced End Session');
            }
        });
    }

Use if (window) to determines if closed or just reload. working for me.

查看更多
骚的不知所云
3楼-- · 2019-01-01 07:54

Its a working solution

export class BootstrapComponent implements OnInit {

  validNavigation = 0;

  constructor(
    private auth: AuthenticationService
  ) { }

  ngOnInit() {
    const self = this;
    self.registerDOMEvents();
  }

  registerDOMEvents() {
    const self = this;
    window.addEventListener('unload', () => {
      if (self.validNavigation === 0) {
        self.endSession();
      }
    });
    document.addEventListener('keydown', (e) => {
      const key = e.which || e.keyCode;
      if (key === 116) {
        self.validNavigation = 1;
      }
    });
  }

  endSession() {
    const self = this;
    self.auth.clearStorage();
  }
}
查看更多
只靠听说
4楼-- · 2019-01-01 07:55

I just tried this and it solved the issue: Create a sessionStorage object which will get destroyed when the user closes the browser. We can check the sessionStorage object to find if the user has closed the browser or refreshed the page(sessionStorage object will not be destroyed on page refresh).

查看更多
登录 后发表回答