Chr*_*nch 4 uiwebview uiwebviewdelegate
有没有办法从UIWebView中检测window.print并对其进行响应?我在我的UiWebView中打印,需要有办法从UIWebView对该事件做出反应.
首先,这是我遇到的解决方案.但是UIWebview不像桌面浏览器那样支持这些事件和API.而且尚未开始matchMedia工作.当我配置打印机时可能会工作!?!
实际的原因是,该网页的媒体类型并没有从改变screen到print在UIWebView的,不像桌面浏览器,所以没有触发,直到这一点.
并且UIWebView没有用于打印直到日期的委托方法.
无论如何,只要有意志,就会有[黑客]方式.两步解决方案.
第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";
}
})();
Run Code Online (Sandbox Code Playgroud)
如果您无权访问HTML或JS文件,请在UIWebView委托中添加以下代码
[self.myWebView stringByEvaluatingJavaScriptFromString:@"(function(){var originalPrintFn = window.print;window.print = function(){window.location = 'your_app_scheme:print';}})();"];
Run Code Online (Sandbox Code Playgroud)
这可以在委托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;
}
Run Code Online (Sandbox Code Playgroud)
在此之后your_handle_to_print,你可以做你的印刷魔术.
希望这可以帮助!