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

Roe*_*ops 1 ios swift wkwebview

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

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

所以我认为我可以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)")
    }

}
Run Code Online (Sandbox Code Playgroud)

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

当我添加一小段延迟后,我会得到正确的结果,但是感觉就像是在砍。

使用这样的观察者

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)
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

也不会对我有帮助,因为我真的需要确保收到的值是最终的高度。

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

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

U. *_*ice 5

因此,您无法控制网页,但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
                })
            }
        })
    }
Run Code Online (Sandbox Code Playgroud)

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