Created
May 27, 2015 15:39
-
-
Save roodkcab/f1757a7aa7ab8ec67483 to your computer and use it in GitHub Desktop.
UIWebView JSContext
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
- (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