gpt4 book ai didi

ios - WKWebView 中 HTML 元素的位置

转载 作者:搜寻专家 更新时间:2023-10-30 23:09:29 25 4
gpt4 key购买 nike

给定一个显示网页的 WKWebView,我如何获得由特定 css 选择器识别的 HTML 元素的位置(在我的 WKWebView 的框架中)?

例子

这里高亮DIV的位置应该是(0, 123)

enter image description here

如果滚动 HTML 内容,同一个 DIV 的位置应该是 (0, 0)

enter image description here

谢谢

最佳答案

这里的问题是 WKWebView 会缩放其内容的大小。在 scrollView 中找到元素框架的技巧是找出 WKWebView 将内容缩放了多少。您可以通过将 ScrollView 的内容大小与 javascript 返回的文档大小进行比较来找到此比例。以下是我能够在 XCode 8.3.2 中运行的 XCode playground 内容。

这将为您提供图像在 ScrollView 中的位置。要获得在 WebView 中的位置,只需减去 scrollview.contentOffset.y

长话短说:

webView.evaluateJavaScript("document.documentElement.clientHeight;") { (value, error) in
self.documentHeight = value as! CGFloat
let zoom = webView.scollView.zoomScale
}

_

import Foundation
import WebKit
import XCPlayground

XCPlaygroundPage.currentPage.needsIndefiniteExecution = true

URLCache.shared = URLCache(memoryCapacity: 0, diskCapacity: 0, diskPath: nil)

let content = "<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Aliquam mauris massa, ornare et ullamcorper a, tristique et odio. Nullam eleifend ex id ante placerat, sit amet feugiat arcu mollis. Sed iaculis lobortis lacus, in fermentum urna sodales at. Integer eget eleifend risus. Aenean feugiat turpis in odio sodales, id volutpat nisi pellentesque. Nunc eleifend nisl nunc, quis blandit nulla posuere ultricies. Nullam varius accumsan neque, vitae imperdiet ante consectetur vel. Fusce ullamcorper eu odio eleifend egestas. <img src=\"https://imgs.xkcd.com/comics/wisdom_of_the_ancients.png\" width=\"98%\"/> Proin elementum odio non massa pulvinar laoreet. Duis tincidunt augue vel placerat euismod. Mauris tincidunt felis at tellus convallis bibendum. Suspendisse purus dolor, lacinia eget tempor feugiat, vestibulum in risus. In non dui nec nisl porttitor pulvinar. Aliquam consectetur nisl at arcu consequat dapibus. Sed ex ante, condimentum vitae diam non, cursus dapibus ligula.<br /><img src=\"https://imgs.xkcd.com/comics/wisdom_of_the_ancients.png\" width=\"98%\"/></p>"

let jsImages = "var images = document.getElementsByTagName('img');" +
"var values = [];" +
"for (var i = 0; i < images.length; i++) {" +
"var rect = images[i].getBoundingClientRect();" +
"values = values.concat(rect.left, rect.top, rect.width, rect.height);" +
"};" +
"values;"

let jsHeight = "document.documentElement.clientHeight;"

class CustomWebView: WKWebView, WKNavigationDelegate {

var imageLocations: [CGRect] = []
var documentHeight: CGFloat?

func getImages() {
self.evaluateJavaScript(jsImages) { (values, error) in
print("=====\nValues from Javascript: \(values)")
if let values = values as? [Any] {
let numImages = values.count / 4 // jsImages returns four-value sets
for set in 0..<numImages {
let offset = set * 4
let imageFrame = self.jsToSwift(x: values[offset] as! CGFloat, y: values[offset+1] as! CGFloat, w: values[offset+2] as! CGFloat, h: values[offset+3] as! CGFloat)
self.imageLocations.append(imageFrame)
}
print("=====\nScrollview content size: \(self.scrollView.contentSize)")
print("=====\nFrames in WebView's ScrollView:\n\(self.imageLocations)\n=====")
}
}
}

func getHeight(callback: @escaping (() -> Void)) {
// Evaluate document height
self.evaluateJavaScript(jsHeight) { (value, error) in
self.documentHeight = value as? CGFloat
callback()
}
}

func jsToSwift(x: CGFloat, y: CGFloat, w: CGFloat, h: CGFloat) -> CGRect {
guard let documentHeight = documentHeight else {
return CGRect.zero
}
let zoom = scollView.zoomScale
let swiftX = x * zoom
let swiftY = y * zoom
let swiftW = w * zoom
let swiftH = h * zoom
return CGRect(x: swiftX, y: swiftY, width: swiftW, height: swiftH)
}

func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
self.getHeight { [weak self] (error) in
self?.getImages()
}
}

}

let webView = CustomWebView(frame: CGRect.zero, configuration: WKWebViewConfiguration())
webView.navigationDelegate = webView
webView.loadHTMLString(content, baseURL: nil)

示例输出:

=====
Values from Javascript: Optional(<__NSArrayM 0x610000049510>(
8,
1528,
485,
270,
8,
2878,
485,
270
)
)
=====
Scrollview content size: (123.0, 791.0)
=====
Frames in WebView's ScrollView:
[(2.0, 382.0, 121.25, 67.5), (2.0, 719.5, 121.25, 67.5)]
=====

关于ios - WKWebView 中 HTML 元素的位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38720981/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com