iOS7之后苹果推出一个用于OC和JS交互的框架JavaScriptCore.h
一、OC调用JS
<html>
<header>
<meta http-equiv="Content-Type" content="text/html"; charset="UTF-8"/>
<title>zhaoName制作的网页</title>
</header>
<script Type = "text/javascript">
function login()
{
return 100;
}
</script>
<body>
电话:10086
<button style="background:red; width:120px; height:30px;">call</button>
</body>
</html>
调用JavaScriptCore中的方法
- (void)webViewDidFinishLoad:(UIWebView *)webView
{
// JavaScriptCore
JSContext *content = [self.webView valueForKeyPath:@"documentView.webView.mainFrame.javaScriptContext"];
// 获取网页的标题
JSValue *value = [content evaluateScript:@"document.title"];
self.title = value.toString;
// 调用JS中函数
[content evaluateScript:@"login()"];
}
二、JS调用OC
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf8">
<script language="javascript">
function colorClick() {
setColor(67,205,12,0.5);
}
</script>
</head>
<body>
<h1>这是按钮调用</h1>
<input type="button" value="修改背景色" onclick="colorClick()" />
</body>
</html>
改变背景色
JSContext *context = [self.webView valueForKeyPath:@"documentView.webView.mainFrame.javaScriptContext"];
__weak typeof(self) weakSelf = self;
context[@"setColor"] = ^() {
NSArray *args = [JSContext currentArguments];
if (args.count < 4) return;
CGFloat r = [[args[0] toNumber] floatValue];
CGFloat g = [[args[1] toNumber] floatValue];
CGFloat b = [[args[2] toNumber] floatValue];
CGFloat a = [[args[3] toNumber] floatValue];
weakSelf.view.backgroundColor = [UIColor colorWithRed:r/255.0 green:g/255.0 blue:b/255.0 alpha:a];
};