Capturing window.print() from a WKWebView

6.8k views Asked by At

I'm trying to capture the window.print() javascript call from a WKWebView with my app to actually show a print dialog and allow them to print from a button presented on the page (instead of a button inside my app). Does anyone know the best way to accomplish this?

Currently, for me, clicking a link that calls window.print() just does nothing but fire the decidePolicyForNavigationAction delegate method and I couldn't find anything relevant in there.

2

There are 2 answers

2
Steve E On BEST ANSWER

Figured it out just after posting (obviously)... Hopefully this helps someone else.

When creating your web view...

let configuration = WKWebViewConfiguration()
let script = WKUserScript(source: "window.print = function() { window.webkit.messageHandlers.print.postMessage('print') }", injectionTime: WKUserScriptInjectionTime.AtDocumentEnd, forMainFrameOnly: true)
configuration.userContentController.addUserScript(script)
configuration.userContentController.addScriptMessageHandler(self, name: "print")
self.webView = WKWebView(frame: CGRectZero, configuration: configuration)

Then just adopt the WKScriptMessageHandler protocol in your view controller and add the required method...

func userContentController(userContentController: WKUserContentController, didReceiveScriptMessage message: WKScriptMessage) {
    if message.name == "print" {
        printCurrentPage()
    } else {
        println("Some other message sent from web page...")
    }
}

func printCurrentPage() {
    let printController = UIPrintInteractionController.sharedPrintController()
    let printFormatter = self.webView.viewPrintFormatter()
    printController?.printFormatter = printFormatter

    let completionHandler: UIPrintInteractionCompletionHandler = { (printController, completed, error) in
        if !completed {
            if let e = error? {
                println("[PRINT] Failed: \(e.domain) (\(e.code))")
            } else {
                println("[PRINT] Canceled")
            }
        }
    }

    if let controller = printController? {
        if UIDevice.currentDevice().userInterfaceIdiom == .Pad {
            controller.presentFromBarButtonItem(someBarButtonItem, animated: true, completionHandler: completionHandler)
        } else {
            controller.presentAnimated(true, completionHandler: completionHandler)
        }
    }
}
2
kfix On

there is an undocumented delegate for hooking window.print()s

class MyApp: WKUIDelegate {
  func makeWebview() {
      ...
      self.webview.UIDelegate = self
  }
  func _webView(webView: WKWebView!, printFrame: WKFrameInfo) {
      println("JS: window.print()")
      printCurrentPage()
  }     
}