簡體   English   中英

為什么我的 javascript function 僅在 iOS Z50DE9BC68C93DC32D8C7C9059347176 中不起作用?

[英]Why does my javascript function not work only in iOS Safari?

我正在使用 C# 和 ASP.NET 核心構建網站。 web 頁面之一有一個按鈕,該按鈕應該使用 javascript 在輸入框中填寫您的地理位置。 當我單擊按鈕時,我無法在 iOS 中獲取 Safari 以運行腳本。 它似乎在我測試過的其他任何地方都有效(Edge 上的 PC 桌面、Chrome、Firefox、iOS 設備在 Firefox 和 Chrome 中)。

這是function,它嵌入在html頁面底部,其中按鈕為:

<script>
    var form = document.getElementById("locinput");
    function getLocation() {
        if (navigator.geolocation) {
            navigator.geolocation.getCurrentPosition(prefillLocation);
        } else {
            x.innerHTML = "Geolocation is not supported by this browser.";
        }
    }

    function prefillLocation(position) {
        form.value = position.coords.latitude + ', ' + position.coords.longitude;
    }
</script>

我嘗試將這個 function 以多種不同的方式連接到按鈕上。

<input id="clickMe" type="button" value="Get GeoLoc" mousemove="getLocation();" onclick="getLocation();" />
<button value="iosbutton" type="button" mousedown="getLocation();" onclick="getLocation();">iOS Button</button>
<a id="iosButton"class="btn" data-g-label="button1" href="javascript:getLocation();">Get Location</a>
<input type="button" value="Test" onmousedown="javscript:getLocation();" />

在所有其他瀏覽器中,上述每個“按鈕”都有效。 在 iOS 的 Safari 中,沒有任何反應。

我通過用警報 function 替換我的 getLocation() function 進行了完整性檢查,如下所示:

<input type="button" value="Test" onmousedown="javscript:alert('Hello');" />

這在 iOS Safari 上工作得很好。 這讓我相信有某種內置的安全性不允許自定義腳本。 但我確信有一種正確的方法可以做到這一點。

有人可以幫我確定為什么會發生這種情況以及如何使我的自定義 function 在 Safari 中為 iOS 工作嗎?

非常感謝!

好的,運行一些測試后的一些事情:

  1. 上面的“按鈕”沒有任何問題,Mac 上的 Safari 和 iOS 都響應onclick="function()"就好了。

  2. 如果頁面不是通過https:訪問的,Safari 將拒絕所有對geolocation的訪問。 嘗試使用http:訪問geolocation :將引發可在控制台中查看的錯誤,否則該錯誤將無聲。

  3. 如果 Safari 嘗試通過https訪問geolocation ,瀏覽器會彈出一個對話框,上面寫着“網站 [your_site_name] 想使用您當前的位置。”,帶有“不允許”和“允許”按鈕。

在此處輸入圖像描述

如果用戶設法克服所有這些障礙, geolocation就會起作用。

測試代碼:

 <html> <head> </head> <body> <form id="locinput"> <input id="clickMe" type="button" value="Get GeoLoc" onclick="getLocation();"/> <button value="iosbutton" type="button" onclick="getLocation();">iOS Button </button> <a id="iosButton" class="btn" data-g-label="button1" href="#" onclick="getLocation();">Get Location</a> <input type="button" value="Test" onclick="getLocation();"/> </form> <script> const form = document.getElementById('locinput'); function getLocation () { console.log('getLocation()'); if (navigator.geolocation) { navigator.geolocation.getCurrentPosition(prefillLocation); } else { alert('Geolocation is not supported by this browser.'); } } function prefillLocation (position) { form.value = position.coords.latitude + ', ' + position.coords.longitude; } </script> </body> </html>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM