6

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

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

4

2 回答 2

12

在发布后(显然)想通了......希望这对其他人有所帮助。

创建 Web 视图时...

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 协议并添加所需的方法...

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)
        }
    }
}
于 2014-11-30T23:46:10.847 回答
0

有一个未记录的委托用于挂钩 window.print()s

class MyApp: WKUIDelegate {
  func makeWebview() {
      ...
      self.webview.UIDelegate = self
  }
  func _webView(webView: WKWebView!, printFrame: WKFrameInfo) {
      println("JS: window.print()")
      printCurrentPage()
  }     
}
于 2015-02-05T08:25:10.863 回答