在 WKWebView 中获取静态页面的最终渲染高度

Getting the final rendered height of a static page in a WKWebView

在我的应用程序中,我使用 WKWebView 加载具有静态内容的网页。

我想在 WKWebView 中完全呈现网页后立即知道 contentSize 的高度。

所以我想我可以为此使用 webView:didFinishNavigation: 委托:

import UIKit
import WebKit

class ViewController: UIViewController, WKNavigationDelegate, WKUIDelegate {

    @IBOutlet weak var webView: WKWebView!

    override func viewDidLoad() {
        super.viewDidLoad()

        webView.navigationDelegate = self
        webView.uiDelegate = self

        webView.load(URLRequest(url: URL(string: "https://www.rockade.nl/testpage/testpage.php")!))
    }

    func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
        print("finished loading: height=\(webView.scrollView.contentSize.height)")
    }

}

此代码的问题是此委托在页面完全呈现之前被调用,所以我得到了不同的高度结果,甚至是 0 的值。

当我添加一个小的延迟时,我得到了正确的结果,但这感觉像是一个 hack。

像这样使用观察者

var myContext = 0
webView.scrollView.addObserver(self, forKeyPath: "contentSize", options: .new, context: &myContext)

override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
        if context == &myContext {
            print(webView.scrollView.contentSize.height)
        } else {
            super.observeValue(forKeyPath: keyPath, of: object, change: change, context: context)
        }
    }
}

对我也没有帮助,因为我真的需要确定接收到的值是最终高度。

提示:我无法控制网页,因此无法使用 javascript。

我希望有人能指出我正确的方向!

因此您无法控制网页,但 html dom 不会逐页更改。所以你可以使用脚本来获取页面的高度。

也许这对你有帮助:

        func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
        webView.evaluateJavaScript("document.readyState", completionHandler: { (complete, error) in
            if complete != nil {
                webView.evaluateJavaScript("document.body.scrollHeight", completionHandler: { (height, error) in
                    // Here is your height
                })
            }
        })
    }

PS:您也可以尝试 'document.body.offsetHeight' 而不是滚动高度。