简单代码如下:
-(void)addBtn
{
//按钮
UIButton *btn=[UIButton buttonWithType:UIButtonTypeCustom];
btn.frame=CGRectMake(0, 0, 100, 40);
[btn addTarget:self action:@selector(btnClick) forControlEvents:UIControlEventTouchUpInside];
[btn setTitle:@"btn" forState:UIControlStateNormal];
[btn setImage:[UIImage imageNamed:@"hotLine"] forState:UIControlStateNormal];
[btn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
[self.view insertSubview:btn aboveSubview:self.webView];
}
-(void)btnClick{
//首先创建JSContext 对象(此处通过当前webView的键获取到jscontext)
JSContext *context=[self.webView valueForKeyPath:@"documentView.webView.mainFrame.javaScriptContext"];
NSString *alertJS=@"callSelf()"; //准备执行的js代码
[context evaluateScript:alertJS];//通过oc方法调用js的alert
}
HTML:
<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<title></title>
</head>
<script type="text/javascript">
function callOC(value1,value2){
zwlog(value1,value2);
}
function callSelf(){
alert('test js OC');
}
</script>
<body bgcolor="#a9a9a9">
<div style="text-align: center;margin-top: 50px">
<input type="button" value="确定" onClick="callOC('11111','1')" />
</div>
</body>
</html>