因工作原因,最近要用到x联的绑卡界面,但发现x联的绑卡界面属于网页,用户体验太差,为了干掉网页高度设置0,实现App原生体现效果,只能使用UIWebview的JS注入
优点:用户体验好了,不用看见烦人的网页
缺点:如果x联的页面标签换了,也要改变(必须了解JS基础)
[webView stringByEvaluatingJavaScriptFromString:@“”];
或:
import
JSContext * context = [webView valueForKeyPath:@”documentView.webView.mainFrame.javaScriptContext”];
[context evaluateScript:@””];
1、JS数据注入input单文本编辑框 代码(infoA属于数据数组)
NSString * header = [NSString stringWithFormat:@”var script = document.createElement(‘script’);script.type = ‘text/javascript’;”];
NSString * input = @”var child = document.getElementsByTagName(‘input’);”;
input属于网页标签,按照注入的不同换成不同标签
NSString * JsS = [NSString stringWithFormat:@”%@%@”,header,input];
NSString * bodys = [NSString stringWithFormat:@”%@var objArray= new Array();”,JsS];
for (int i = 0; i < infoA.count; i++)
{
bodys = [bodys stringByAppendingFormat:@"objArray['%d']='%@';child[%d].value='%@';",i,infoA[i],i,infoA[i]];
}
return bodys;
2、JS注入模拟按钮自动点击,此处模拟x联的短信验证码发送ID=@”sendCode”;
NSString * header = [NSString stringWithFormat:@”var script = document.createElement(‘script’);script.type = ‘text/javascript’;”];
return NSString stringWithFormat:@”%@document.getElementById(‘%@’).click();”,header,ID];
3、JS根据class标签数据注入
-(NSString )g8byClassName:(NSString )ClassName
parms:(NSArray *)parms
{
NSString * classN = [NSString stringWithFormat:@"var child=document.getElementsByClassName('%@');",ClassName];
NSString * JsS = [NSString stringWithFormat:@"%@%@",header,classN];
NSString * bodys = [NSString stringWithFormat:@"%@var objArray= new Array();",JsS];
for (int i = 0; i < parms.count; i++)
{
bodys = [bodys stringByAppendingFormat:@"objArray['%d']='%@';child[%d].value='%@';",i,parms[i],i,parms[i]];
}
return bodys;
}
4、JS注入 根据class标签模拟按钮自动点击
-(NSString )clickByClassName:(NSString )ClassName
{
NSString * bodys = [NSString stringWithFormat:@”%@var childClick=document.getElementsByClassName(‘%@’);”,header,ClassName];
return [bodys stringByAppendingFormat:@”if(childClick.length>=0){childClick[0].click();}”];
}
5、注入JS函数
context[@”jsContext”] = self;
[context evaluateScript:@”jsContext.jsCallback(‘1’);”];
-(void)jsCallback:(NSString *)JSs;
{
CXTLog(@"函数参数 = %@",JSs);
}