Skip to content

Instantly share code, notes, and snippets.

@pkuecuekyan
Last active June 17, 2024 17:44
Show Gist options
  • Save pkuecuekyan/f70096218a6b969e0249427a7d324f91 to your computer and use it in GitHub Desktop.
Save pkuecuekyan/f70096218a6b969e0249427a7d324f91 to your computer and use it in GitHub Desktop.
Adjust height of WKWebView frame based on scrollHeight of the webView's content
// Since the WKWebView has no sizeToFit() method, increase the frame height of the webView to
// match the height of the content's scrollHeight
//
// The WKWebView's `navigationDelegate` property needs to be set for the delegate method to be called
func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
if webView.isLoading == false {
webView.evaluateJavaScript("document.body.scrollHeight", completionHandler: { [weak self] (result, error) in
if let height = result as? CGFloat {
webView.frame.size.height += height
}
})
}
}
@elmyn
Copy link

elmyn commented Nov 6, 2021

I'm getting too small content with view port.

@vishalkevin11
Copy link

Thanks a lot. This works like a charm.

@kneskoromny
Copy link

kneskoromny commented Mar 12, 2024

The problem for me was the document.body.width, even if meta tag still very small...
So I fix running a script before:
document.body.style.width = '{width}px'

Thanx! It's work for me. Your answer save me :)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment