Search code examples
macoswkwebview

How to support Zoom like Safari with WKWebView on macOS


In Safari the user can enlarge the content by using the Zoom commands, like Command +. This enlarges not only the content, including font size, but it also adjusts the content to remain between the window margins.

I want to achieve the same feature with WKWebView on macOS, but I don't know how to do that when using the loadRequest() command on the web view control.

I have tried the following, without much success:

  • Inject javascript like "document.getElementsByTagName('body')[0].style.webkitTextSizeAdjust='150%'". It seems that webkitTextSizeAdjust is not supported anymore on the macOS version of WKWebView, see https://trac.webkit.org/changeset/145168/webkit.
  • Use the magnification property. This works, but this simply enlarges (or minimises) everything, without adjusting the content to remain between the control width (viewport), like Safari does.

Please take note that I'm using loadRequest(), not loadHTMLString().


Solution

  • I encountered the same prblem, and found a solution. You need to set an JavaScript code injection to the WkWebView configuration. The scale number needs to be set in the JavaScript code.

    The full code is shown below:

    NSString *jScript = @"document.body.style.zoom = 0.8";
    WKUserScript *wkUScript = [[WKUserScript alloc] initWithSource:jScript injectionTime:WKUserScriptInjectionTimeAtDocumentEnd forMainFrameOnly:YES];
    
    WKUserContentController *wkUController = [[WKUserContentController alloc] init];
    [wkUController addUserScript:wkUScript];
    
    WKWebViewConfiguration *configuration = [[WKWebViewConfiguration alloc] init];
    configuration.userContentController = wkUController;
    
    WKWebView *webContentView = [[WKWebView alloc] initWithFrame:NSMakeRect(0, 0,sizeWidth, sizeHeight) configuration:configuration];