Access the JavaScriptCore engine of a UIWebView

aspyct picture aspyct · Oct 29, 2013 · Viewed 8.1k times · Source

I just discovered a new framework available in iOS7: JavaScriptCore.

It looks awesome, but how can I access the runtime/context of a UIWebView?

Answer

TomSwift picture TomSwift · Nov 23, 2013

There is no official mechanism for this. But there are two approaches I know about to get the JSContext. I probably wouldn't use either in a shipping app.

  1. Use KVC to access internal UIWebView properties. Explained in detail in this blog post: http://blog.impathic.com/post/64171814244/true-javascript-uiwebview-integration-in-ios7
JSContext *ctx = [webView valueForKeyPath:@"documentView.webView.mainFrame.javaScriptContext"];
  1. Add a magic method to NSObject via a category. Explained in more detail, here: https://github.com/TomSwift/UIWebView-TS_JavaScriptContext
@implementation NSObject (magic)
- (void) webView: (id) unused didCreateJavaScriptContext: (JSContext*) ctx forFrame: (id) frame
{
    // ...
}
@end