Question

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.

Was it helpful?

Solution

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!

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top