Search code examples
iosobjective-c

Intercept request with WKWebView


Now i'm using UIWebView and with canInitWithRequest: of NSURLProtocol i can intercept all requests and do with it what I want.

In the new WKWebView this method there isn't, and i not found something similar.

Has someone resolved this problem?


Solution

  • I see that after 5 years this question still generates curiosity, so I describe how I solved it and about some main problems I faced up. As many who answered here, I have implemented WKURLSchemeHandler and used new schemes.

    First of all the URL that wkwebview launches must not be HTTP (or HTTPS) but one of yours new schemes.

    Example

    mynewscheme://your-server-application.com

    In your WKWebViewConfiguration conf, I set the handler:

    [conf setURLSchemeHandler:[CustomSchemeHandler new] forURLScheme:@"mynewscheme"];
    [conf setURLSchemeHandler:[CustomSchemeHandler new] forURLScheme:@"mynewschemesecure"];
    

    In CustomSchemeHandler I have implemented webView:startURLSchemeTask: and webView:stopURLSchemeTask:.

    In my case I check if the request is for a file that I just saved locally, otherwise I change actual protocol ("mynewscheme or "mynewschemesecure") with http (or https) and I make request by myself.

    At this point I solved the "interception problem".

    In this new way we have the webview "location" (location.href via javascript) with my new scheme and with it new problems started.

    • First problem is that my applications work mainly with javascript, and document.cookie has stopped working. I'm using Cordova framework, so I've develeped a plugin to set and get cookie to replace document.cookie (I had to do this, because, obviously, I have also http header set-cookie).

    • Second problem is that I've got a lot of "cross-origin" problems, then I changed all my urls in relative url (or with new schemes)

    • Third problem is that browser automatically handle server port 80 and 443, omitting them, but has now stopped (maybe because of "not http location"). In my server code I had to handle this.

    Writing down these few rows I admit that it seems to was an easy problem to solve, but I ensure that find out a workaround, how to solve it and integrate with the infinite amount of code has been hard. Every step towards the solution corresponded to a new problem.