UIWebView JavaScript losing reference to iOS JSContext namespace (object) UIWebView JavaScript losing reference to iOS JSContext namespace (object) javascript javascript

UIWebView JavaScript losing reference to iOS JSContext namespace (object)


The page load can cause the WebView (and UIWebView which wraps WebView) to get a new JSContext.

If this was MacOS we were talking about, then as shown in the section on WebView in the 2013 WWDC introduction "Integrating JavaScript into Native Apps" session on Apple's developer network (https://developer.apple.com/videos/wwdc/2013/?id=615), you would need to implement a delegate for the frame load and initialise your JSContext variables in your implementation of the selector for webView:didCreateJavaScriptContext:forFrame:

In the case of IOS, you need to do this in webViewDidFinishLoad:

-(void)webViewDidFinishLoad:(UIWebView *)view{    self.js = [view valueForKeyPath:@"documentView.webView.mainFrame.javaScriptContext"]; // Undocumented access to UIWebView's JSContext    self.js[@"ios"] = self;}

The previous JSContext is still available to Objective-C since you've kept a strong reference to it.


check this UIWebView JSContext

The key point is register a javascript object once JSContext changed. I use a runloop observer to check is there any network operation finished, once it finished, I'll get the changed JSContext, and register any object I want to it.

I didn't try if this work for iframe, if u have to register some objects in iframe, try this

NSArray *frames = [_web valueForKeyPath:@"documentView.webView.mainFrame.childFrames"];[frames enumerateObjectsUsingBlock:^(id frame, NSUInteger idx, BOOL *stop) {    JSContext *context = [frame valueForKeyPath:@"javaScriptContext"];    context[@"Window"][@"prototype"][@"alert"] = ^(NSString *message) {        NSLog(@"%@", message);    };}];