IOS WKWebView Improperly Calculating Height When There Is Embedded Tweet
Solution 1:
With the help several posts on stackoverflow (especially: Twitter Uncaught TypeError: undefined is not a function), and my colleague who is a web developer, I managed to find a solution to this issue. Basically, the idea is to add a script to the webview configuration if there is an embedded tweet in a html string which webview needs to load. After that we should implement userContentController didReceive message function and in it we should evaluate the height of a webview.
Here is the code which should go before webview.loadHtmlString method:
if htmlString.contains("platform.twitter.com/widgets.js") {
let twitterJS: String = "window.twttr = (function(d, s, id) {var js, fjs = d.getElementsByTagName(s)[0],t = window.twttr || {};if (d.getElementById(id)) return t;js = d.createElement(s);js.id = id;js.src = \"https://platform.twitter.com/widgets.js\";fjs.parentNode.insertBefore(js, fjs);t._e = [];t.ready = function(f) {t._e.push(f);};return t;}(document, \"script\", \"twitter-wjs\"));twttr.ready(function (twttr) {twttr.events.bind('loaded', function (event) {window.webkit.messageHandlers.callbackHandler.postMessage('TWEET');});});"
let userScript = WKUserScript(source: twitterJS, injectionTime: .atDocumentEnd, forMainFrameOnly: false)
webViewx.configuration.userContentController.removeAllUserScripts()
webViewx.configuration.userContentController.addUserScript(userScript)
webViewx.configuration.userContentController.add(self, name: "callbackHandler")
}
First there is a check if a html string has a substring which is an embedded tweet. Script assigned to let twitterJS is something we got from twitter web page. Last line is important in a sense that it gives the name to our script.
Actual height evaluation is done like this:
func userContentController(_ userContentController: WKUserContentController, didReceive message: WKScriptMessage) {
if message.name == "callbackHandler" {
print(message.body)
webViewx.evaluateJavaScript("document.body.offsetHeight", completionHandler: { (height, error) in
if let error = error {
print(error.localizedDescription)
return
}
if let height = height as? CGFloat{
if height > self.kontejnerHeight.constant {
self.kontejnerHeight.constant = height
}
}
})
}
}
Hopefully this will help the others as well.
Post a Comment for "IOS WKWebView Improperly Calculating Height When There Is Embedded Tweet"