从WKWebView捕获window.print() [英] Capturing window.print() from a WKWebView

查看:353
本文介绍了从WKWebView捕获window.print()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用我的应用程序从WKWebView捕获window.print()javascript调用,以实际显示打印对话框并允许它们从页面上显示的按钮打印(而不是我的应用程序内的按钮) 。有没有人知道实现这个目标的最佳方法?

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?

目前,对我来说,单击一个调用window.print()的链接只会触发decisionPolicyForNavigationAction委托方法,我在那里找不到任何相关内容。

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.

推荐答案

在发布之后想出来(显然)......希望这有助于别人。

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)

然后只是采用WKScriptMessageHandler协议在您的视图控制器和添加所需的方法...

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)
        }
    }
}

这篇关于从WKWebView捕获window.print()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆