Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Map Custom URL protocol to HTTP (using NSURLProtocol?)

I have an application using a WebKit WebView and I'd like to map URL's that are loaded in this WebView with a custom URL protocol to a different HTTP URL. For example, say I am loading:

custom://path/to/resource

I would like to internally actually load:

http://something-else.com/path/to/resource

In other words, the custom protocol serves almost as a shorthand. I can't however use -webView:resource:willSendRequest:redirectResponse:fromDataSource:, because I want WebKit to actually believe this is the URL in question, not to simply redirect from one to the other.

So far I've been attempting to use a custom NSURLProtocol subclass. However, this is proving trickier than I first thought because, at least to my understanding, I will have to do the actual loading myself in the NSURLProtocol subclass' startLoading method. I'd like a way to just hand off the work to the existing HTTP protocol loader, but I can't find an easy way to do this.

Does anyone have a recommendation for this, or perhaps an alternative way to solve this issue?

Thanks!

like image 272
Francisco Ryan Tolmasky I Avatar asked May 12 '10 06:05

Francisco Ryan Tolmasky I


1 Answers

I use the policy delegate. It has some disadvantages, but it's simple and sufficient for my needs. I do something like this:

 - (void)webView:(WebView *)webView decidePolicyForNavigationAction:(NSDictionary *)actionInformation request:(NSURLRequest *)request frame:(WebFrame *)frame decisionListener:(id < WebPolicyDecisionListener >)listener;

{
    if ([request.URL.scheme isEqualToString:@"custom"]) {

        // do something interesting
        // like force the webview to load another URL

        [listener ignore];
        return;
    }

    [listener use];
}

For my use, I also need to stop the propagation of the JS events. So I usually place the URL in an onclick event handler that calls window.event.stopPropagation(); after setting the location.href.

It's not very fancy, but it's a very flexible and very simple way to communication a JS event to cocoa.

like image 156
isaiah Avatar answered Nov 03 '22 10:11

isaiah