如何在Cocoa / WebKit应用程序中从Javascript调用Objective-C方法?

时间:2008-09-18 13:21:33

标签: javascript objective-c cocoa webkit

我有一个使用WebView显示HTML界面的Cocoa应用程序。我如何从HTML界面中的Javascript函数调用Objective-C方法?

4 个答案:

答案 0 :(得分:12)

这是developer.apple.com记录的。

答案 1 :(得分:3)

如果您想在iPhone应用程序中执行此操作,则需要使用UIWebViewDelegate方法进行操作:shouldStartLoadWithRequest:

这个api http://code.google.com/p/jsbridge-to-cocoa/为你做了。它非常轻巧。

答案 2 :(得分:3)

相当绿色,Apple的文档对我来说几乎无法使用,所以我在Cocoa中提供了从javascript调用Objective C方法的概念证明,反之亦然,尽管后者更容易。

首先确保您将webview视为setFrameLoadDelegate:

[testWinWebView setFrameLoadDelegate:self];

您需要告诉webview在加载后立即查看特定对象:

- (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;
}

关键是,如果您要调用多个方法,则需要在isSelectorExcludedFromWebScript方法中将它们全部排除,并且需要javascript调用以映射到webScriptNameForSelector中的ObjC方法。

概念文件的完整项目证明: https://github.com/bytestudios/JS-function-and-ObjC-method-connector

答案 3 :(得分:1)

我有一个使用NimbleKit的解决方案。它可以从Javascript调用Objective C函数。