1

I tried to fit the HTML content into my web view and for that, I tried to add a different kind of script into it and by using constraint, I changed its height as well. Now, the problem is that the width of the content not fits into WkWebView content and exceeds it. I checked another application where it just fits into the content but not in my case.

Here are the scripts and code I already to tried to resolve the issue:

  1. Using meta data into the header and append it to HTML string

    var headerString = "<header><meta name='viewport' content='width=device-width, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0'></header>"
    headerString.append(data)
    webView.loadHTMLString(data, baseURL: nil)
    
  2. Inject JS into WKWebView using WKUserScript

    private func getZoomDisableScript() -> WKUserScript {
        let source = """
        var meta = document.createElement('meta');
                    meta.setAttribute('name', 'viewport');
                    meta.setAttribute('content', 'width = device-width, initial-scale = 1.0, minimum-scale = 1.0, maximum-scale = 1.0);
                    document.getElementsByTagName('head')[0].appendChild(meta);
        """
    
        return WKUserScript(source: source, injectionTime: .atDocumentEnd, forMainFrameOnly: true)
    }
    
    webView.configuration.userContentController.addUserScript(getZoomDisableScript())
    

And here is the code to evaluate JS

func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
    self.webView.evaluateJavaScript("document.readyState", completionHandler: { [self] (complete, error) in
        if complete != nil {
            webView.evaluateJavaScript("document.getElementsByTagName('body')[0].style.fontFamily =\"-apple-system\"")
            webView.evaluateJavaScript("document.body.scrollHeight", completionHandler: { [self] (height, error) in
                if !isHeightRendered {
                    delegate?.renderedHeight(height as! CGFloat)
                    isHeightRendered = true
                }
            })
        }
    })
}

Also tried different ways mentioned here but none works for me. Here is the screenshot of the other app that fits contents into WebView and for them, it works.

enter image description here

The result I get

enter image description here

So, Is there anything I am doing wrong or Is there anything to add to fits into the web view content?

Bhavin Bhadani
  • 22,224
  • 10
  • 78
  • 108

0 Answers0