我正在尝试使用我的应用程序从WKWebView捕获window.print()javascript调用,以实际显示打印对话框并允许它们从页面上显示的按钮打印(而不是我的应用程序内的按钮) 。有谁知道实现这个目标的最佳方法?
目前,对我来说,单击一个调用window.print()的链接只会触发decisionPolicyForNavigationAction委托方法,但我找不到任何相关内容。
答案 0 :(得分:8)
在发布之后(显然)想出来......希望这有助于其他人。
创建网络视图时......
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)
}
}
}
答案 1 :(得分:0)
有一个undocumented委托用于挂钩window.print()s
class MyApp: WKUIDelegate {
func makeWebview() {
...
self.webview.UIDelegate = self
}
func _webView(webView: WKWebView!, printFrame: WKFrameInfo) {
println("JS: window.print()")
printCurrentPage()
}
}