In Safari you can increase and decrease the font size. How can I achieve the same effect with WKWebView?
3 Answers
The codes suggested by Inna used to work but stopped working from iOS10.3. I did some research and found that we need to make a slight change to it, just changing "%%" to a single "%".
So JS code should be:
let js = "document.getElementsByTagName('body')[0].style.webkitTextSizeAdjust='\(fontSize)%'"
I got this info from Apple Developer forum. https://forums.developer.apple.com/thread/51079
Swift 5 solution:
Implement WKNavigationDelegate
and in viewDidLoad
:
webView.navigationDelegate = self
then in didFinish
:
func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
let js = "document.getElementsByTagName('body')[0].style.webkitTextSizeAdjust='200%'"//dual size
webView.evaluateJavaScript(js, completionHandler: nil)
}
Assume that you have fontUpdatedHeight integer which gives you the exact fontsize.
Just create string like that:
NSString *jsString = [[NSString alloc] initWithFormat:@"document.getElementsByTagName('body')[0].style.webkitTextSizeAdjust= '%lu%%'",(unsigned long)fontUpdatedHeight];
And execute the NSString
[self.WKWebView stringByEvaluatingJavaScriptFromString:jsString];
-
1This used to work great, but it stopped working from latest Xcode (Xcode8.3.2). Is there anyone who is facing the same problem? Is there any way to fix it? Apr 29, 2017 at 10:56
-
-
Oh, really? Which version of Xcode are you using and what is iOS version of your device? I am using XCode 8.3.2 & iOS10.3.1. There seems to be people like me at Apple Developer Forum too (please scroll to the bottom)forums.developer.apple.com/thread/51079 May 6, 2017 at 10:31
-
3WKWebView doesn't have a
stringByEvaluatingJavaScriptFromString:jsString
method; that's UIWebView. May 8, 2017 at 4:05 -
It works perfect with UIWebView but not with WKWebView but UIWebView is depreciated– johnnyAug 8, 2018 at 2:03