WKWebView是否可以关闭位置权限?

Is it possible to turn off location permission in WKWebView?

请问是否可以让WKWebView不显示定位权限提示? ("website.com" 想使用您的当前位置)我相信它正在显示,因为该网站包含 google 地图。我对在其他 SO 问题中显示的位置预加载位置不感兴趣。我只是不想在 WKWebView 中使用位置。有没有办法阻止位置权限提示出现?我尝试注入以下 javascript 但它不起作用。

        let contentController = WKUserContentController()

        let scriptSource = "navigator.geolocation.getCurrentPosition = function(success, error, options) { // }; navigator.geolocation.watchPosition = function(success, error, options) { // }; navigator.geolocation.clearWatch = function(id) { // };"
        let script = WKUserScript(source: scriptSource, injectionTime: .atDocumentEnd, forMainFrameOnly: true)
        contentController.addUserScript(script)

        let config = WKWebViewConfiguration()
        config.userContentController = contentController

        webView = WKWebView(frame: .zero, configuration: config)
        self.view = webView

一些注意事项:

  1. .atDocumentEnd 意味着您的脚本将在页面加载后执行,这可能会导致 javascript 在您劫持位置功能之前询问位置 运行; .atDocumentStart
  2. 你可能会得到更好的结果
  3. 脚本中有 // 个序列,这可能会导致脚本的其余部分被解释为注释,从而导致注入不正确的 JS
  4. 函数的签名似乎与 HTML 5 Geolocation API 不匹配,但考虑到我们处于 JS 世界并且函数体是空的,这可能没有什么不同。

尝试解决上述问题,这可能会导致您需要的行为。

我遇到了同样的问题,上面的方法只部分奏效了。我认为这个问题更正确的解决方案是使用 PERMISSION_DENIED 错误代码调用错误回调,以便网站可以在位置访问被拒绝时执行所需的操作。这是我最终使用的代码(我只需要覆盖 getCurrentPosition,但如果需要,您也可以添加 watchPosition):

let removeLocationJS = """
navigator.geolocation.getCurrentPosition = function(success, error, options) {
    error({
        PERMISSION_DENIED: 1,
        code: 1
    });
};
"""

let removeLocation = WKUserScript(source: removeLocationJS, injectionTime: .atDocumentStart, forMainFrameOnly: true)
contentController.addUserScript(removeLocation)

let config = WKWebViewConfiguration()
config.userContentController = contentController

let webView = WKWebView(frame: .zero, configuration: config)

真的,如果您的 Info.plist 中没有条目,WKWebView 似乎应该为您解决这个问题,它应该会自动执行此操作(并且可能会向控制台吐出一条消息让你知道它确实如此)。我要去归档雷达...