为什么我的 javascript 功能仅在 iOS Safari 中不起作用?

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

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

这是函数,它嵌入在 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();" />

在所有其他浏览器中,上述每个 "buttons" 都有效。在 iOS 的 Safari 中,没有任何反应。

我通过将 getLocation() 函数替换为警报函数来进行健全性检查,如下所示:

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

这在 iOS Safari 上工作得很好。这让我相信有某种内置的安全性不允许自定义脚本。但我确信有一个正确的方法来做到这一点。

谁能帮我确定为什么会这样,以及如何让我的自定义功能在 iOS 的 Safari 中工作?

非常感谢!

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

  1. 上面的 "buttons" 没问题,Mac 和 iOS 上的 Safari 都可以很好地响应 onclick="function()"

  2. 如果页面未通过 https: 访问,Safari 将拒绝对 geolocation 的所有访问。尝试使用 http: 访问 geolocation 将抛出一个在控制台中可见的错误,否则错误将是无声的。

  3. 如果 Safari 尝试通过 https 访问 geolocation,浏览器将抛出一个对话框,显示类似 "The website [your_site_name] would like to use your current location." 的内容,其中 "Don't Allow" 和"Allow" 个按钮。

如果用户设法克服所有这些障碍,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>