Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Capturing window.print() from a WKWebView

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.

like image 207
Steve E Avatar asked Nov 16 '14 09:11

Steve E


1 Answers

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)
        }
    }
}
like image 162
Steve E Avatar answered Sep 21 '22 14:09

Steve E