我有一个使用WebView显示HTML界面的Cocoa应用程序。我该如何从HTML界面内的JavaScript函数调用Objective-C方法?
此文档记录在developer.apple.com网站上。
由于苹果的文档对我来说相当晦涩难懂,因此我制作了一个概念验证,用于在Cocoa中从JavaScript调用Objective-C方法以及反之。尽管后者更容易,但考虑到我的经验水平,这仍然很困难。
首先,请确保您的Web视图已设置为setFrameLoadDelegate:
[testWinWebView setFrameLoadDelegate:self];
- (void)webView:(WebView *)sender didClearWindowObject:(WebScriptObject *)windowScriptObject forFrame:(WebFrame *)frame {
//add the controller to the script environment
//the "ObjCConnector" object will now be available to JavaScript
[windowScriptObject setValue:self forKey:@"ObjCConnector"];
}
然后是通信业务:
// a few methods to log activity
- (void)acceptJavaScriptFunctionOne:(NSString*) logText {
NSLog(@"acceptJavaScriptFunctionOne: %@",logText);
}
- (void)acceptJavaScriptFunctionTwo:(NSString*) logText {
NSLog(@"acceptJavaScriptFunctionTwo: %@",logText);
}
//this returns a nice name for the method in the JavaScript environment
+(NSString*)webScriptNameForSelector:(SEL)sel {
NSLog(@"%@ received %@ with sel='%@'", self, NSStringFromSelector(_cmd), NSStringFromSelector(sel));
if(sel == @selector(acceptJavaScriptFunctionOne:))
return @"functionOne"; // this is what you're sending in from JS to map to above line
if(sel == @selector(acceptJavaScriptFunctionTwo:))
return @"functionTwo"; // this is what you're sending in from JS to map to above line
return nil;
}
//this allows JavaScript to call the -logJavaScriptString: method
+ (BOOL)isSelectorExcludedFromWebScript:(SEL)sel {
NSLog(@"isSelectorExcludedFromWebScript: %@", NSStringFromSelector(sel));
if(sel == @selector(acceptJavaScriptFunctionOne:) ||
sel == @selector(acceptJavaScriptFunctionTwo:))
return NO;
return YES;
}
我有一个使用NimbleKit的解决方案。它可以从Javascript调用Objective C函数。