Home > Software design >  Full Page screenshot of WKWebView for macOS
Full Page screenshot of WKWebView for macOS

Time:10-25

This is a macOS app, I'm trying to take a full page screenshot of a webview, but i'm unable to get the screenshot of the full page.

Screenshot function.

    func takescreenshot(
        _ webView: WKWebView,
        didFinish navigation: WKNavigation!) {
    
    
    let configuration = WKSnapshotConfiguration()

    configuration.afterScreenUpdates =  true
    
    webView.takeSnapshot(with: configuration) { (image, error) in
        
        
        if let image = image {
            
         //Save Image
            
        }
    }


}

from the answers I've seen here the solution seems to be setting the webview scrollview offset, but this is only available for ios. This is the error i get:

Value of type "WKWebView" has no member "scrollView"

CodePudding user response:

I guess the problem is caused by an internal scroll view that optimizes drawing for scrolling - by redrawing only parts that are soon to be visible.

To overcome this, you can temporarily resize the web view to it's full content extent. I know it's not an ideal solution, but you may derive better one based on this idea.

   webView.evaluateJavaScript("[document.body.scrollWidth, document.body.scrollHeight];") { result, error in
        if let result = result as? NSArray {
            
            let orig = webView.frame
            webView.frame = NSRect(x: 0, y: 0, width: (result[0] as! NSNumber).intValue, height: (result[1] as! NSNumber).intValue)

            let configuration = WKSnapshotConfiguration()
            webView.takeSnapshot(with: configuration) { image, error in
                if let image = image {
                    NSPasteboard.general.clearContents()
                    NSPasteboard.general.setData(image.tiffRepresentation, forType: .tiff)
                }
            }
            
            webView.frame = orig
        }
    }
  • Related