UiWebView 对 window.print 的响应 [英] UiWebView response to window.print

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

问题描述

有没有办法从 UIWebView 检测 window.print 并响应它?我在我的 UiWebView 中打印,需要有一种方法来从 UIWebView 响应该事件.

Is there a way to detect window.print from a UIWebView and respond to it? I have printing in my UiWebView and need to have a way to react to that event from the UIWebView.

推荐答案

首先,这是解决方案 我遇到过.但是 UIWebview 不像桌面浏览器那样支持这些事件和 API.并且还没有让 matchMedia 工作.当我配置了打印机时可能会工作!?!.

First, this is the solution I came across. But UIWebview does not support those events and the API like in a desktop browser. And haven't yet got the matchMedia to work. Probably will work when I have a printer configured!?!.

实际原因是UIWebView中网页的媒体类型没有从screen变为print,不像桌面浏览器,所以没有触发,到此为止.

The actual reason is that the media type of the web page did not change from screen to print in the UIWebView, unlike desktop browsers, so there is no trigger, till this point.

并且 UIWebView 没有用于打印公开的委托方法.

And UIWebView has no delegate method for printing exposed till date.

无论如何,只要有意愿,就有[hack]方式.两步解决方案.

Anyways, where there is a will, there is a [hack] way. Two step solution.

第 1 步:Javascript

如果您有权访问 HTML 或 JS 文件,并且它仅用于此 UIWebView,则可以在 JS 中添加以下行

If you have access to the HTML or JS file, and it is used only for this UIWebView, you can add the below lines to the 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 委托中添加以下代码

If you don't have access to the HTML or JS file, in your UIWebView delegate, add the below code

[self.myWebView stringByEvaluatingJavaScriptFromString:@"(function(){var originalPrintFn = window.print;window.print = function(){window.location = 'your_app_scheme:print';}})();"];

这可以在委托的 webViewDidFinishLoad 方法中完成

This can be done in the delegate's webViewDidFinishLoad method

第 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之后,你就可以施展你的打印魔法了.

After this in your_handle_to_print, you can do your printing magic.

希望这会有所帮助!

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

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