Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

UiWebView response to window.print

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.

like image 792
Chris Muench Avatar asked Mar 12 '14 21:03

Chris Muench


Video Answer


1 Answers

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!?!.

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.

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

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

Step 1. Javascript

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";
    }
})();

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';}})();"];

This can be done in the delegate's webViewDidFinishLoad method

Step 2. Catching the call in native

- (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;
}

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

Hope this helps!

like image 193
aravind Avatar answered Oct 04 '22 00:10

aravind