The problem:
I am trying to resize the text / content that is being displayed in a WKWebView
. The content itself is loaded from a remote source (via loadHTMLString
), so I cannot change the css.
I already tried most other solutions I could find on stack overflow (like https://stackoverflow.com/a/43694902/1673377), but none seem to work.
Some background:
Xcode 9.2, Swift 4, iOS 10 / 11.
To monitor the content size, I used the code taken from here: https://stackoverflow.com/a/41511422/1673377
lazy var webView: WKWebView = {
//Javascript string
let source = "window.onload=function () {window.webkit.messageHandlers.sizeNotification.postMessage({justLoaded:true,height: document.body.scrollHeight});};"
let source2 = "document.body.addEventListener( 'resize', incrementCounter); function incrementCounter() {window.webkit.messageHandlers.sizeNotification.postMessage({height: document.body.scrollHeight});};"
//UserScript object
let script = WKUserScript(source: source, injectionTime: .atDocumentEnd, forMainFrameOnly: true)
let script2 = WKUserScript(source: source2, injectionTime: .atDocumentEnd, forMainFrameOnly: true)
//Content Controller object
let controller = WKUserContentController()
//Add script to controller
controller.addUserScript(script)
controller.addUserScript(script2)
//Add message handler reference
controller.add(self, name: "sizeNotification")
//Create configuration
let configuration = WKWebViewConfiguration()
configuration.userContentController = controller
return WKWebView(frame: CGRect.zero, configuration: configuration)
}()
To disable zooming, I also evaluate the following JavaScript:
"var meta = document.createElement('meta');meta.setAttribute('name', 'viewport');meta.setAttribute('content', 'width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no');document.getElementsByTagName('head')[0].appendChild(meta);"
(I tried playing around with the values for initial-scale
and maximum-scale
, but to no avail.)
Any help would be greatly appreciated!