Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>You can get a JSContext from a UIWebView with a key path:</p> <pre><code>UIWebView *webView = [[UIWebView alloc] init]; JSContext *ctx = [webView valueForKeyPath:@"documentView.webView.mainFrame.javaScriptContext"]; ctx[@"document"][@"body"][@"style"][@"background"] = @"steelblue"; </code></pre> <p>Apple never got around to documenting any of the new JavaScriptCore APIs, so I'm not sure if this counts as an internal/undocumented API or not. I have an app approved that uses this method.</p> <p><strong>Update</strong>: Another alternative solution suggested at <a href="https://github.com/TomSwift/UIWebView-TS_JavaScriptContext" rel="noreferrer">https://github.com/TomSwift/UIWebView-TS_JavaScriptContext</a> is to make a category on <code>NSObject</code> and use it to implement WebKit's documented <code>didCreateJavaScriptContext</code> delegate callback. To paraphrase that implementation, you can just call <code>[NSObject contextForWebView:myWebView]</code> to grab the JSContext for a UIWebView:</p> <pre><code>@implementation NSObject(JSContextTracker) + (NSMapTable *)JSContextTrackerMap { static NSMapTable *contextTracker; static dispatch_once_t onceToken; dispatch_once(&amp;onceToken, ^{ contextTracker = [NSMapTable strongToWeakObjectsMapTable]; }); return contextTracker; } - (void)webView:(id)unused didCreateJavaScriptContext:(JSContext *)ctx forFrame:(id)alsoUnused { NSAssert([ctx isKindOfClass:[JSContext class]], @"bad context"); if (!ctx) return; NSMapTable *map = [NSObject JSContextTrackerMap]; static long contexts = 0; NSString *contextKey = [NSString stringWithFormat:@"jsctx_%@", @(contexts++)]; [map setObject:ctx forKey:contextKey]; ctx[@"JSContextTrackerMapKey"] = contextKey; // store the key to the map in the context itself } + (JSContext *)contextForWebView:(UIWebView *)webView { // this will trigger didCreateJavaScriptContext if it hasn't already been called NSString *contextKey = [webView stringByEvaluatingJavaScriptFromString:@"JSContextTrackerMapKey"]; JSContext *ctx = [[NSObject JSContextTrackerMap] objectForKey:contextKey]; return ctx; } @end </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload