有没有办法确定WKWebView或SFSafariViewController视图中某个点的元素?

时间:2018-09-19 18:01:13

标签: ios wkwebview sfsafariviewcontroller

我想知道Web视图中特定点“下”的元素。例如,在下面的屏幕截图中,我想知道点550x,275y处的元素。我希望得到结果:

<img alt=​"Typhoon Mangkhut approaching the Philippines on September 14" src=​"/​/​upload.wikimedia.org/​wikipedia/​commons/​thumb/​3/​30/​Mangkhut_2018-09-14_0750Z.jpg/​140px-Mangkhut_2018-09-14_0750Z.jpg" width=​"140" height=​"111" srcset=​"/​/​upload.wikimedia.org/​wikipedia/​commons/​thumb/​3/​30/​Mangkhut_2018-09-14_0750Z.jpg/​210px-Mangkhut_2018-09-14_0750Z.jpg 1.5x, /​/​upload.wikimedia.org/​wikipedia/​commons/​thumb/​3/​30/​Mangkhut_2018-09-14_0750Z.jpg/​280px-Mangkhut_2018-09-14_0750Z.jpg 2x" data-file-width=​"1219" data-file-height=​"963">​

enter image description here

1 个答案:

答案 0 :(得分:0)

如果网络视图支持,则可以让javascript确定其中的内容,然后将其报告给网络视图。抱歉,我没有运行此代码,目前没有测试它的方法。

如果您无法在页面上添加JavaScript,则必须在WKWebView .evaluateJavaScript

中完成所有操作

使用以下命令查找元素值:

var elem = document.elementFromPoint(550, 275);

然后通过创建自定义方案请求将其告知您的Web视图。您可以这样操作:

var iframe = document.createElement("IFRAME");
iframe.setAttribute("src", "customScheme://" + JSON.stringify(elem);
document.documentElement.appendChild(iframe);
iframe.parentNode.removeChild(iframe);
iframe = null;

在webview委托中拦截它。

public func webView(_ webView: WKWebView,
                    decidePolicyFor navigationAction: WKNavigationAction,
                    decisionHandler: @escaping (WKNavigationActionPolicy) -> Void) {
    let url = navigationAction.request.url
    if(url.range(of:"customScheme://") != nil){
         // this is your reported info
    }
    return true
}

这种方法只会告诉您与Web浏览器坐标相关的元素,而不是它在设备屏幕上的位置。如果您想通过设备位置进行操作,则必须进行翻译,然后通过在设备上调用一些JavaScript将坐标传递到Web视图。

相关问题