1>.先设置委托:WebFrameLoadDelegate
设置Javascript foo 对象的值。
- - (void)webView:(WebView *)sender windowScriptObjectAvailable:(WebScriptObject *)windowScriptObject
- {
- NSString *myFoo = @"zczhustring";
- [windowScriptObject setValue:myFoo forKey:@"foo"]; //foo is javascript varible
- }
2.调用Javascript函数function addImage(string){}
- 调用javascript函数
- -(void)callJavaScriptFun
- {
- WebView *myWebView;
- WebScriptObject * win = [myWebView windowScriptObject];
- NSArray *args = [NSArray arrayWithObjects:@"zzczzc",nil]; //arguments,参数
- //函数调用不返回
- [win callWebScriptMethod:@"addImage" withArguments:args];
- //函数调用后返回
- id rvalue= [win evaluateWebScript:@"addImage('zzczzc')"];
- NSLog(@"%@", rvalue);
- }
3>.JavaScript invoke objectiove-c method
javascript调用自己的一个函数:-(id)setJSvalue:(NSString *)str;
- a)
- - (void)webView:(WebView *)sender windowScriptObjectAvailable:(WebScriptObject *)windowScriptObject
- {
- //set method key
- [windowScriptObject setValue:self forKey:@"setJSvalue"];
- }
-
- b)在主线程类中重载如下函数
- ///重载
- + (BOOL)isSelectorExcludedFromWebScript:(SEL)selector
- {
- return NO;
- }
- + (BOOL)isKeyExcludedFromWebScript:(const char *)property {
- if (strcmp(property, "name") == 0) {
- return NO;
- }
- return YES;
- }
- + (NSString *)webScriptNameForSelector:(SEL)sel
- {
- if (sel == @selector(bar:))
- return @"bar";
- if (sel == @selector(setJSvalue:))
- return @"setJSvalue";
- return nil;
- }
- document.write("call objective-c function<br>");
- var myjs = window.setJSvalue;
- string = "argument";
- var name = myjs.setJSvalue_(string);
- document.write("call objective-c function<br>");
最后:objective-c 与 javascript 函数对应规则:
Objective –C 函数 在javascript 调用函数名应该为
Objective-C selector | Default script name for selector |
setFlag: | setFlag_ |
setFlag:forKey:withAttributes: | setFlag_forKey_withAttributes_ |
propertiesForExample_Object: | propertiesForExample$_Object_ |
set_$_forKey:withDictionary: | set$_$$_$_forKey_withDictionary_ |
余下问题:
如果要调用其他类的方法,却不成功。待续。。。