Talking about window. onbeforeunload of event calling ajax

  • 2021-07-01 06:20:55
  • OfStack

Often there is a need for users not to log off at a fixed point when leaving an web page, which will lead to the session not being destroyed in time. In order to realize the automatic logout function when the user leaves the page, it is necessary to send the logout command in the onbeforeunload event handler of the web page. This place is mostly implemented with Ajax. Sometimes cross-domain access is involved. There is a browser compatibility problem in this place.

There are two incompatibilities in browsers when dealing with this requirement:

1. The incompatibility when dealing with Ajax is solved by jQuery.

2. Incompatibility when sending Ajax requests

The main code is as follows:


function logout() { 
        var logoutURL = "xxxx"; // Used to log off the user url 
        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 higher security level when dealing with js, and the permissions that js can use in many IE and Chrome are restricted in Friefox, so through


if(userAgent.indexOf("msie")>-1) { //IE
          
        }else { //FireFox Chrome
          
        }

This code to determine the current browser type.

For Firefox, the compatible code for Chrome is as follows:


$.ajax({ url: logoutURL, async: false });

async needs to be set to false, that is, synchronous, and true asynchronous mode cannot be adopted, otherwise the request may not be sent out. In fact, Chrome is also applicable to the following code for IE, in the browser will be automatically sent logout command, but click the browser refresh button also want to automatically log off the user, Chrome can only use the above line of code to send out logout request

Compatible codes for IE are as follows:


$.ajax({ url: logoutURL, crossDomain: true, async: false, dataType: "jsonp" });

crossDomain is set to true to address cross-domain access issues, which can be ignored if the problem does not exist. Preferably, the async attribute is also set to false, and true is fine. dataType: The attribute "jsonp" is also used to solve the cross-domain access problem. When used with crossDomain, there is no cross-domain problem, so these two attributes can be omitted.

The above code passed the test in IE9, Chrome27 and Firefox21.


Related articles: