There is often a need for this, that is, when leaving a certain web page, the user does not necessarily click to log out, which will cause the session to not be destroyed in time. In order to realize the automatic logout function when the user leaves the page, the logout command needs to be sent in the onbeforeunload event handling function of the web page. This place is mostly implemented using Ajax. Sometimes it also involves cross-domain access issues. There is a browser compatibility problem in this place.
There are two points incompatibility of browsers when dealing with this requirement:
1. Incompatibility when dealing with Ajax, jQuery is used to solve it here.
2. Incompatibility when sending Ajax request
The main code is as follows:
function logout() { var logoutURL = "xxxx"; //url used to log out the user if (logoutURL == "") return; var userAgent = navigator.userAgent.toLowerCase(); if(userAgent.indexOf("msie")>-1) { //IE $.ajax({ url: logoutURL, crossDomain: true, async: false, dataType: "jsonp" }); }else { //FireFox Chrome $.ajax({ url: logoutURL, async: false }); } } window.onbeforeunload = function () { logout(); };Code description:
Firefox has a high security level when processing js. Many permissions that js can use in IE and Chrome are restricted in Friefox, so
if(userAgent.indexOf("msie")>-1) { //IE }else { //FireFox Chrome }This code determines the current browser type.
The compatible code for Firefox and Chrome is as follows:
$.ajax({ url: logoutURL, async: false });async needs to be set to false, that is, it is synchronous, and true asynchronous method cannot be used, otherwise the request may not be sent out. In fact, Chrome is also suitable for the following IE code. When the browser is turned off, the logout command will be automatically sent. However, when clicking the browser's refresh button, it also hopes to automatically log out the user. Chrome can only use the above line of code to issue a logout request.
The compatible code for IE is as follows:
$.ajax({ url: logoutURL, crossDomain: true, async: false, dataType: "jsonp" });CrossDomain is set to true to solve cross-domain access problems. If this problem does not exist, this property can be ignored. It is best to set the async attribute to false, and true is also OK. dataType:"jsonp" property is also used to solve cross-domain access problems. It is used in conjunction with crossDomain. There is no cross-domain problem. These two properties can be omitted.
The above code was tested in IE9, Chrome27, and Firefox21.
The above is the brief discussion that the editor brings to you about the window.onbeforeunload() event calls ajax (title). I hope everyone supports Wulin.com~