Skip to content

Instantly share code, notes, and snippets.

@roodkcab
Created May 27, 2015 15:39
Show Gist options
  • Save roodkcab/f1757a7aa7ab8ec67483 to your computer and use it in GitHub Desktop.
Save roodkcab/f1757a7aa7ab8ec67483 to your computer and use it in GitHub Desktop.
UIWebView JSContext
- (void)observeJSContext
{
CFRunLoopRef runLoop = CFRunLoopGetCurrent();
// This is a idle mode of RunLoop, when UIScrollView scrolls, it jumps into "UITrackingRunLoopMode"
// and won't perform any cache task to keep a smooth scroll.
CFStringRef runLoopMode = kCFRunLoopDefaultMode;
CFRunLoopObserverRef observer = CFRunLoopObserverCreateWithHandler
(kCFAllocatorDefault, kCFRunLoopBeforeWaiting, true, 0, ^(CFRunLoopObserverRef observer, CFRunLoopActivity _) {
JSContext *context = [_web valueForKeyPath:@"documentView.webView.mainFrame.javaScriptContext"];
if (![_context isEqual:context]) {
CFRunLoopRemoveObserver(runLoop, observer, runLoopMode);
_context = context;
_context[@"iOS"] = self;
void(^alert)(NSString *) = ^(NSString *message) {
NSLog(@"%@", message);
};
_context[@"Window"][@"prototype"][@"alert"] = alert;
}
});
CFRunLoopAddObserver(runLoop, observer, runLoopMode);
}
- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType
{
[self observeJSContext];
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment