如果无法访问UIWebView的运行时,为什么要在iOS7中使用JavaScriptCore? [英] Why use JavaScriptCore in iOS7 if it can't access a UIWebView's runtime?

查看:161
本文介绍了如果无法访问UIWebView的运行时,为什么要在iOS7中使用JavaScriptCore?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是对此博客的回应:

http://blog.bignerdranch.com/3784-javascriptcore-and-ios-7/

来自iOS开发者的想法SO?

Thoughts from the iOS devs on SO?

推荐答案

您可以从UIWebView获取带有关键路径的JSContext:

You can get a JSContext from a UIWebView with a key path:

UIWebView *webView = [[UIWebView alloc] init];
JSContext *ctx = [webView valueForKeyPath:@"documentView.webView.mainFrame.javaScriptContext"];
ctx[@"document"][@"body"][@"style"][@"background"] = @"steelblue";

Apple从来没有记录任何新的JavaScriptCore API,所以我不确定这是不是是否计入内部/未记录的API。我有一个已批准使用此方法的应用。

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.

更新 https://github.com/TomSwift/UIWebView-TS_JavaScriptContext 是在 NSObject 并使用它来实现WebKit记录的 didCreateJavaScriptContext 委托回调。要解释该实现,您只需调用 [NSObject contextForWebView:myWebView] 来获取UIWebView的JSContext:

Update: Another alternative solution suggested at https://github.com/TomSwift/UIWebView-TS_JavaScriptContext is to make a category on NSObject and use it to implement WebKit's documented didCreateJavaScriptContext delegate callback. To paraphrase that implementation, you can just call [NSObject contextForWebView:myWebView] to grab the JSContext for a UIWebView:

@implementation NSObject(JSContextTracker)

+ (NSMapTable *)JSContextTrackerMap {
    static NSMapTable *contextTracker;
    static dispatch_once_t onceToken;
    dispatch_once(&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

这篇关于如果无法访问UIWebView的运行时,为什么要在iOS7中使用JavaScriptCore?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆