UIWebView与JavaScript常用交互代码
最近打算换个工作环境,所以就没怎么写东西。面试中,被问到一些在UIWebView和WKWebView中如何与JavaScript交互的问题,索性在这里复习一下,有的都忘了。
CSS常用参数:
是否允许用户选择元素的内容,选择值包括:
1.auto:用户可以元素内的内容
2.none:用户不能选择任何内容
3.text:用户只能选择元素内的文本
常用语句:
1.禁用用户选择
[self.webView stringByEvaluatingJavaScriptFromString:@"document.documentElement.style.webkitUserSelect='none'"];
2.禁用长按弹出框
[self.webView stringByEvaluaingJavaScriptFromString:@"document.documentElement.style.webkitTouchCallout='none'"];
3.获得UIWebView的URL地址
NSString *currentURL = [webView stringByEvaluatingJavaScriptFromString:@"document.location.href"]; NSLog(@"currentURL == %@",currentURL);
4.获得UIWebView的标题
NSString *theTitle = [webView stringByEvaluatingJavaScriptFromString:@"document.title"]; NSLog(@"theTitle ==%@",theTitle);
5.通过name(获得或设置)界面元素的value值
NSString *js_email_ByName = [webView stringByEvaluatingJavaScriptFromString:@"document.getElementByName('email')[0].value='hello';"]; NSLog(@"js_email_ByName==%@",js_email_ByName); NSString *js_password_byName = [webView stringByEvaluatingJavaScriptFromString:@"document.getElementByName('pwd')[0].value='hello';"]; NSString *js_phone_ByName = [webView stringByEvaluatingJavaScriptFromString:@"document.getElementByName('tel')[0].value='hello';"]; NSlog(@"js_phone_ByName==%@",js_phone_ByName);
6.通过id获取与设置与上述类似
只是将@“”中的内容换成document.getElementByIdx_x_x('phone自己替换').value='';
7.提交表单
NSString *js_forms = [webView stringByEvaluatingJavaScriptFromString:@"document.forms[0].submit();"]; NSLog(@"js_forms==%@",js_forms);
8.获得body与body之间的HTML
NSString *allHTML = [webView stringByEvaluatingJavaScriptFromString:@"document.body.innerHTML"]; NSLog(@"allHTML:%@",allHTML);
9.使UIWebView的输入框获得焦点,但是无法弹出iPhone键盘
[webView stringByEvaluatingJavaScriptFromString:@"document.querySelector('#saySome').focus()"]; [webView stringByEvaluatingJavaScript:@"document.getElementByIdx_x("saySome").scrollntoView("true")"];
10.改变webView尺寸时对应改变web page尺寸
[webView stringByEvaluatingJavaScriptFromString:[NSString stringWithFormat:@"document.querySelector('meta[name=viewport]').setAttribute('content','width=%d;',false);"(int)webView.frame.size.width]];
先罗列这么多,后面再更新