views:

1661

answers:

4

If you try to send an Ajax request, a JSONP request, or even a window.name request on unload, Safari and Chrome run the code, but the server never sees the request. My theory is the thread of execution never allows the script tag to run before it changes the page. Here is a test page with the JSONP test. This code (and Ajax and window.name) creates a request for test.html in Firefox and IE7, but not Safari:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"&gt;
<html>
    <head>
    </head>
    <body>

        <script language="javascript" type="text/javascript">
            window.onunload = function(){
       var encode = "UTF-8";
       var script = document.createElement('script');
       script.type = 'text/javascript';
          script.src= "/test.html";
          script.charset= encode;
       document.body.appendChild(script)
      }
        </script>

    </body>
</html>

Anyone know a good way to get around this? More specifically, anyone know of a way to force Safari to send a request on unload? The only solution I've found (which doesn't really help in my case) is synchronous XHR.

A: 

Sorry I don't have an answer, but I have seen the same problem. An ajax application that I am building also needs to send onunload (which works fine in FireFox and IE but not Opera). I also tried document.onunload and window.onbeforeunload but to no avail. If I find an answer I will make sure to post. (written 5-29-2009)

OK, I realized that I had made a mistake and so I tried it again. It turns out that window.onbeforeunload will work for what you were wanting. In my application, when the user leaves the page, the xmlhttprequest object makes a post request so that I can see the time they left the page. With onunload chrome will not let the request reach the server but with onbeforeunload I was able to get it to work. I am still looking for a good solution for Opera which has the same problem..

And sorry I posted when I didn't have the answer yet, I'm new here. I should have just replied with a comment.

Don't use the Answer feature if you don't have an answer.
musicfreak
A: 

It works Good, thank u hackartist!

A: 

I Think that the onbeforeunload did not work well in safari and opera,for Opera ,there is a problem in its event Model ,for safari I just know I cant send my request to Server with the onbeforeunload event,but other browsers support this event well,anybody can solve this problem?

kun
A: 

Thanks for the tip on using synchronous XHR request. That DOES work with Safari (4.0.4) and the onbeforeunload event.

ocdgeek