KPWebViewInterceptor

www.knowledgeisporridge.com

This is a pretty straightforward mechanism to enable Javascript invocation of Objective-C code in your ViewControllers.

The KPWebViewInterceptor class does the heavy lifting, acting as a delegate that sits between your WebView and ViewController. To use this functionality simply instantiate a new KPWebViewInterceptor and attach it to your WebView and ViewController using the attach method.

How it works

The KPWebViewInterceptor class simply responds to the WebView's shouldStartLoadWithRequest delegate method. If the request's absolute URL is prefixed with "invoke:", the request is trapped. If it doesn't the shouldStartLoadWithRequest delegate is propergated to your ViewController. The objc_msgsend function provided by the KPWebViewInterceptor.js file provides a consistant approach to formatting and invoking requests.

Calls made using the objc_msgsend function are automatically invoked on your ViewController. You do not need to implement any additional functionality or protocols.

Examples

Calling:
objc_msgsend('sayHello');
Will automatically invoke:
- (void)sayHello;

Calling:
objc_msgsend( 'say', 'the message' );
Will automatically invoke:
- (void)say:(NSString *)message;

Calling:
objc_msgsend( 'say', 'the message', 'withTitle', 'title here' );
Will automatically invoke:
- (void)say:(NSString *)message withTitle:title;

Working examples

The following links invoke methods in KPWebViewInterceptorViewController.

Say hello!
Say!
Say!