1

我正在使用 C# 和 ASP.NET Core 构建一个网站。其中一个网页有一个按钮,该按钮应该使用 javascript 在输入框中填写您的地理位置。当我单击按钮时,我无法让 iOS 中的 Safari 运行脚本。它似乎适用于我测试过的其他任何地方(Edge 上的 PC 桌面、Chrome、Firefox、Firefox 和 Chrome 中的 iOS 设备)。

这是函数,它嵌入在按钮所在的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>

我尝试以多种不同的方式将此功能附加到按钮上。

<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 中,没有任何反应。

我通过用警报函数替换我的 getLocation() 函数进行了完整性检查,如下所示:

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

这在 iOS Safari 上运行良好。这让我相信有某种内置的安全性不允许自定义脚本。但我确信有一种正确的方法可以做到这一点。

有人可以帮我确定为什么会发生这种情况以及如何使我的自定义功能在 iOS 版 Safari 中工作吗?

非常感谢!

4

1 回答 1

0

好的,运行一些测试后的一些事情:

  1. 上面的“按钮”没有任何问题,Mac 和 iOS 上的 Safari 都可以正常响应onclick="function()"

  2. geolocation如果页面不是通过.Safari 访问,Safari 将拒绝所有访问https:。尝试访问geolocationwithhttp:将引发在控制台中可见的错误,否则该错误将保持沉默。

  3. 如果 Safari 试图通过 访问geolocationhttps浏览器会弹出一个对话框,上面写着“网站 [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>

于 2020-04-17T01:03:26.273 回答