2013-08-02 17 views
0

沒有工作,我有這樣的腳本:XMLHttpRequest的內部`onbeforeunload`處理器在Opera

<script language="JavaScript" type="text/javascript"> 

    function enter() { 
     this.chrono = new Date().getMilliseconds(); 
    } 

    function leave() { 
     this.chrono = new Date().getMilliseconds() - this.chrono; 

     alert("test" + this.chrono); 

      var blockingRequest = new XMLHttpRequest(); 
      blockingRequest.open("GET", "visitor_log/ajax_store_visit_duration.php?visit_duration=" + this.chrono, false); // async = false 
      blockingRequest.send(); 

     return null; 
    } 

    window.onload = enter; 
    window.onbeforeunload = leave; 
</script> 

PHP部分(visitor_log/ajax_store_visit_duration.php文件):

<?php 

if(isset($_GET["visit_duration"])) 
{ 
    $text = $_GET["visit_duration"]; 

    logtxt($text); 

    echo "OK"; 
} 
else die("application error"); 

function logtxt($text) 
{ 
    $myFile = "test.txt"; 
    $fh = fopen($myFile, 'wb'); 
    fwrite($fh, $text); 
    fclose($fh); 
} 

?> 

它可以在Chrome完美,但在Opera中不起作用。

如何使它跨瀏覽器?

回答

0

它不應該在任何地方工作。 getMilliseconds()返回日期對象的毫秒部分,而不是某個最終的毫秒值。該值始終低於1000.在比較您的量級時無用。你真正想要的是世界時間。

(new Date()).valueOf()應該給你一個值,你可以使用。

這可能是部分答案,因爲您實際上並未指定什麼不起作用。

+0

好的,不過那個事件根本不起作用...... – Kamil

+0

好吧,有點研究)Google)在這裏討論了這個問題:http://stackoverflow.com/questions/14645011/window-onbeforeunload-and -window-onunload-is-not-working-in-firefox-safari-o。這可能是相關的。 – 2013-08-02 18:21:08