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 會正常執行web

解釋自定義協議

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; }
相關文章
相關標籤/搜索