2014-11-03 58 views
0

當要求獲取地理位置權限時,用戶將獲得一個彈出窗口,要求獲取地理位置權限。Javascript:如何以編程方式在X秒後終止警報

if (navigator.geolocation) { 
    navigator.geolocation.getCurrentPosition(successCallback, errorCallback); 
} 

假設用戶5秒後沒有反應,我想「強制errorCallback」。 我該怎麼做?

謝謝。

回答

1

根據MDNgetCurrentPosition()的第三個參數是一個選項對象,允許您指定超時值。

該文檔指定超時值是允許等待GPS位置的最長時間,因此您必須對其進行測試以確定它是否包含等待用戶響應權限提示的時間。

0

我想,這或多或少取決於瀏覽器如何處理用戶沒有回答關於權限問題的事實。

總之,解決方法可能是一個給定的時間後重定向:

<html> 
    <body> 
     <h1>My page</h1> 

     <script> 
      var userdidnothing=false; 

      function TimeoutHandler() { 
       if (!userdidnothing) { 
        window.location.href="http://www.yoursecondpage.com"; 
       } 
      } 

      setTimeout("TimeoutHandler();",5000); 

      if (navigator.geolocation) { 
       navigator.geolocation.getCurrentPosition(function() { 
        userdidnothing=true; 
        alert("SUCCESS"); 
       }, 
       function() { 
        alert("ERROR"); 
       }); 
      } 
     </script> 

     Geolocation feature is helpful, if you need to know where you are... 
    </body> 
</html> 
相關問題