簡體   English   中英

如何在Cocoa / WebKit應用程序中從Javascript調用Objective-C方法?

[英]How to call an Objective-C method from Javascript in a Cocoa/WebKit app?

我有一個Cocoa應用程序,它使用WebView來顯示HTML界面。 我如何從HTML界面中的Javascript函數調用Objective-C方法?

這在developer.apple.com上有記錄。

相當綠色,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

如果你想在iPhone應用程序中這樣做,你需要使用UIWebViewDelegate方法shouldStartLoadWithRequest做一個技巧:

這個api http://code.google.com/p/jsbridge-to-cocoa/為您做到了。 它非常輕巧。

我有一個使用NimbleKit的解決方案。 它可以從Javascript調用Objective C函數。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM