9

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

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

Lorenzo B
  • 33,216
  • 24
  • 116
  • 190
aspyct
  • 3,625
  • 7
  • 36
  • 61

3 Answers3

11

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
kolyuchiy
  • 5,465
  • 2
  • 23
  • 31
TomSwift
  • 39,369
  • 12
  • 121
  • 149
  • Excellent. Error-prone but still nice. I don't see why Apple didn't expose this. – Léo Natan Nov 22 '13 at 23:28
  • Looks interesting! Hopefully it will soon appear in the public API. Until then I'll try your solution :) – aspyct Nov 24 '13 at 09:34
  • Your code on GitHub looks interesting, but doesn't have a license—any chance you could clarify the licensing? – Isaac Jul 31 '14 at 19:56
2

You might like to look at the WWDC 2013 Session Videos on the developer web-site (https://developer.apple.com/wwdc/videos/) and in particular 'Integrating JavaScript into Native Apps' which to quote the description "Introducing a new Objective-C API to JavaScriptCore. iOS developers can now integrate scripting into their apps without having to bundle custom language interpreters. This API builds on top of the existing C API to JavaScriptCore available on Mac, and makes programming with JavaScript much easier and less error-prone." There is a section on using it with WebView e.g. using: -webView:didCreateJavaScriptContext:forFrame:

Stunner
  • 12,025
  • 12
  • 86
  • 145
VaughanR
  • 329
  • 2
  • 8
0

JavaScriptCore exists so that developers have a JavaScript runtime to use from Objective-C. The only way I'm aware of to access the UIWebView runtime is through the stringByEvaluatingJavaScriptFromString: method, which obviously isn't very flexible.

Alex Medearis
  • 176
  • 1
  • 7