首先,这是我遇到的solution。但是 UIWebview 不支持这些事件和 API,就像在桌面浏览器中一样。还没有让matchMedia 工作。可能会在我配置打印机后工作!?!。
实际原因是网页的媒体类型在UIWebView中没有从screen变为print,不像桌面浏览器,所以没有触发,到此为止。
并且 UIWebView 没有用于打印的委托方法。
无论如何,只要有意愿,就会有 [hack] 方式。两步解决方案。
第 1 步。Javascript
如果您可以访问 HTML 或 JS 文件,并且它仅用于此 UIWebView,则可以在 JS 中添加以下行
(function(){
var originalPrintFn = window.print; // Keep it cached in this variable, just in case
window.print = function(){
// Trigger location change
window.location = "your_app_scheme:print";
}
})();
如果您无权访问 HTML 或 JS 文件,请在 UIWebView 委托中添加以下代码
[self.myWebView stringByEvaluatingJavaScriptFromString:@"(function(){var originalPrintFn = window.print;window.print = function(){window.location = 'your_app_scheme:print';}})();"];
这可以在委托的webViewDidFinishLoad 方法中完成
第 2 步。在本机中接听电话
- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType
{
if ([[[request URL] absoluteString] hasPrefix:@"your_app_scheme:"]) {
// Call the given selector
[self performSelector:@selector(your_handle_to_print)];
// Cancel the event, so the webview doesn't load the url
return NO;
}
return YES;
}
在your_handle_to_print 之后,你可以施展你的打印魔法了。
希望这会有所帮助!