14

In Safari you can increase and decrease the font size. How can I achieve the same effect with WKWebView?

Mark
  • 16,906
  • 20
  • 84
  • 117

3 Answers3

12

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

Yuichi Kato
  • 863
  • 7
  • 16
5

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)
}
Mehrdad
  • 1,050
  • 1
  • 16
  • 27
2

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];
Onder OZCAN
  • 1,556
  • 1
  • 16
  • 36
  • 1
    This 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? – Yuichi Kato Apr 29 '17 at 10:56
  • I don't think it's stopped. You should review your codes again? – Onder OZCAN May 05 '17 at 00:08
  • 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)https://forums.developer.apple.com/thread/51079 – Yuichi Kato May 06 '17 at 10:31
  • 3
    WKWebView doesn't have a `stringByEvaluatingJavaScriptFromString:jsString` method; that's UIWebView. – BinaryNate May 08 '17 at 04:05
  • It works perfect with UIWebView but not with WKWebView but UIWebView is depreciated – johnny Aug 08 '18 at 02:03
  • I think now is [self.webview evaluateJavaScript: completion]; – James Rochabrun Dec 01 '18 at 03:09