[[[UIWebView alloc] init] stringByEvaluatingJavaScriptFromString:@"alert(100);"];//oc直接運(yùn)行js代碼
- html代碼
<html>
<!-- 網(wǎng)頁(yè)的描述信息 -->
<head>
<meta charset="UTF-8">
<title>第一個(gè)網(wǎng)頁(yè)</title>
<script>
function login()
{
// 讓webView跳轉(zhuǎn)到百度頁(yè)面(加載百度頁(yè)面)
location.href = 'JavaScript://sendMessage_number2_number3_?100&100&99';
}
</script>
</head>
<!-- 網(wǎng)頁(yè)的具體內(nèi)容 -->
<body>
<button style="background: red; width:100px; height:30px;" onclick="login();">Call</button>
</body>
</html>
-
OC代碼
-(BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType { // url == JavaScript://sendMessage_?200 NSString *url = request.URL.absoluteString; NSString *scheme = @"JavaScript://"; if ([url hasPrefix:scheme]) { // 獲得協(xié)議后面的路徑 path == sendMessage_number2_?200&300 NSString *path = [url substringFromIndex:scheme.length]; // 利用?切割路徑 NSArray *subpaths = [path componentsSeparatedByString:@"?"]; // 方法名 methodName == sendMessage:number2: NSString *methodName = [[subpaths firstObject] stringByReplacingOccurrencesOfString:@"_" withString:@":"]; // 參數(shù) 200&300 NSArray *params = nil; if (subpaths.count == 2) { params = [[subpaths lastObject] componentsSeparatedByString:@"&"]; } // 調(diào)用 [self performSelector:NSSelectorFromString(methodName) withObjects:params]; return NO; } NSLog(@"想加載其他請(qǐng)求,不是想調(diào)用OC的方法"); return YES; } - (id)performSelector:(SEL)selector withObjects:(NSArray *)objects { // 方法簽名(方法的描述) NSMethodSignature *signature = [[self class] instanceMethodSignatureForSelector:selector]; if (signature == nil) { [NSException raise:@"錯(cuò)誤" format:@"%@方法找不到", NSStringFromSelector(selector)]; } // NSInvocation : 利用一個(gè)NSInvocation對(duì)象包裝一次方法調(diào)用(方法調(diào)用者、方法名、方法參數(shù)、方法返回值) NSInvocation *invocation = [NSInvocation invocationWithMethodSignature:signature]; invocation.target = self; invocation.selector = selector; // 設(shè)置參數(shù) NSInteger paramsCount = signature.numberOfArguments - 2; // 除self、_cmd以外的參數(shù)個(gè)數(shù) paramsCount = MIN(paramsCount, objects.count); for (NSInteger i = 0; i < paramsCount; i++) { id object = objects[i]; if ([object isKindOfClass:[NSNull class]]) continue; [invocation setArgument:&object atIndex:i + 2]; } // 調(diào)用方法 [invocation invoke]; // 獲取返回值 id returnValue = nil; if (signature.methodReturnLength) { // 有返回值類(lèi)型,才去獲得返回值 [invocation getReturnValue:&returnValue]; } return returnValue; } - (void)sendMessage:(NSString *)number number2:(NSString *)number2 number3:(NSString *)number3 { NSLog(@"%s %@ %@ %@", __func__, number, number2, number3); }