WebViewのJavaScriptからObjective-Cのメソッドを呼ぶ時の命名規則


WebScripting Protocol Reference の webScriptNameForSelector: に書いてあった。

It is your responsibility to ensure that the returned name is unique to the script invoking this method. If this method returns nil or you do not implement it, the default name for the selector is constructed as follows:


・A colon (“:”) in the Objective-C selector is replaced by an underscore (“_”).


・An underscore in the Objective-C selector is prefixed with a dollar sign (“$”).


・A dollar sign in the Objective-C selector is prefixed with another dollar sign.

非形式プロトコルのwebScriptNameForSelector:メソッドを実装して、呼ばれる名前を対応付けしない場合は、Objective-Cのメソッド名は、こういうルールになると。


下記のような場合はmyTest:がJavaScript側からは、myTest_となる。

//Objective-C
- (void)webView:(WebView *)sender didFinishLoadForFrame:(WebFrame *)frame
{
    WebScriptObject *windowObject = [[sender mainFrame] windowObject];
    [windowObject setValue:self forKey:@"appObject"];
    NSString *message = @"call from Objective-C";
    [windowObject evaluateWebScript:[NSString stringWithFormat:@"test('%@');",message]];
}

- (void)myTest:(NSString *)message
{
    NSString *result=[message stringByAppendingString:@" append myTest string"];
    NSLog(@"%@",result);
    //call from Objective-C append JavaScript string append myTest string
}

//サンプルなので全部のメソッド公開しちゃってるけど、実際にはJavaScriptに公開するメソッドは絞っておくなり、JavaScript側に差し込むObjective-Cの専用クラスを用意するなりする。
+ (BOOL)isSelectorExcludedFromWebScript:(SEL)selector
{
    return NO;
}
//JavaScript
function test(message) {
  var string = " append JavaScript string";
  window.appObject.myTest_(message+string);
}