webView和js交互
Posted Ruby-hua
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了webView和js交互相关的知识,希望对你有一定的参考价值。
与 js 交互
OC 调用 JS
// 执行 js
- (void)webViewDidFinishLoad:(UIWebView *)webView {
NSString *title = [webView stringByEvaluatingjavascriptFromString:@"document.title;"];
NSLog(@"%@", title);
[webView stringByEvaluatingJavaScriptFromString:@"clickme();"];
}
JS 调用 OC
准备代码
- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType {
NSLog(@"%@", request.URL);
return YES;
}
在 OC 中,如果代理方法返回 BOOL 类型,返回 YES 会正常执行
解释自定义协议
href="myfunc:///showMessage:/周末一起玩吧:D"
调用 OC 中的方法 `showMessage:` 显示内容 `郊游怎么样:D`
代码实现
- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType {
NSLog(@"%@", request.URL.scheme);
if ([request.URL.scheme isEqualToString:@"myfunc"]) {
NSLog(@"%@", request.URL.pathComponents);
NSArray *components = request.URL.pathComponents;
NSString *funcName = components[1];
NSString *param = components[2];
SEL func = NSSelectorFromString(funcName);
[self performSelector:func withObject:param];
}
return YES;
}
代码细节
- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType {
NSLog(@"%@", request.URL.scheme);
if ([request.URL.scheme isEqualToString:@"myfunc"]) {
NSLog(@"%@", request.URL.pathComponents);
NSArray *components = request.URL.pathComponents;
if (components.count != 3) {
return NO;
}
NSString *funcName = components[1];
NSString *param = components[2];
SEL func = NSSelectorFromString(funcName);
if ([self respondsToSelector:func]) {
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Warc-performSelector-leaks"
[self performSelector:func withObject:param];
#pragma clang diagnostic pop
}
return NO;
}
return YES;
}
以上是关于webView和js交互的主要内容,如果未能解决你的问题,请参考以下文章
Android-webview和js脚本语言交互的时候怎么获取js方法的返回值