UIWebView与JS的交互
IOS-的UIWebView
UIWebVew是ios开发中较为常用的一个控件。其可以打开网页,加载html,打开文档等。当我们在开发中需要用到一些显示页面时,UIWebView是一个很好的选择。
创建一个UIWebView
的CGRect bouds = [[UIScreen manScreen] applicationFrame];
UIWebView的web视图* = [[UIWebView的页头] initWithFrame:方法界限]
设置属性
//UIWebView默认允许当网页内容处于最顶端时,用户用手指往下拖动,然后露出空白的背景。这份代码能够禁止这种效果。
webView.scrollView.bounces = NO;
//是否与用户交互(即用户能不能控制的WebView)
[web视图setUserInteractionEnabled:YES];
//自动对页面进行缩放以适应屏幕
webView.scalespageToFit = YES;
//自动检测网页上的电话号码,单击可以拨打
webView.detectsPhoneNumbers = YES;
加载内容
NSURL * URL = [NSURL URLWithString:@“http://www.youku.com”]; //创建网址
*的NSURLRequest请求= [的NSURLRequest requestWithURL:URL]; //创建的NSURLRequest
[web视图的loadRequest:请求]; //加载
加载本地HTML页面
//返回HTML文件路径
* NSString的文件路径= [[[一个NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:@“homeDetail.html”];
//读取HTML文件内容
* NSString的htmlString = [NSString的stringWithContentsOfFile:文件路径编码:NSUTF8StringEncoding错误:无];
//替换HTML文件的内容
htmlString = [htmlString stringByReplacingOccurrencesOfString:@“$ {} docContent”withString:[的NSString stringWithFormat:@“%@”,[JSON objectForKey:@“内容”]]];
[web视图loadHTMLString:htmlString BASEURL:[NSURL URLWithString:文件路径]];
UIWebViewDelegate委托代理
//设置委托对象
webView.delegate =自我;
//选择要实现的委托方法
////当网页视图被指示载入内容而得到通知。应当返回YES,这样会进行加载。
- (BOOL)web视图:(UIWebView的*)web视图shouldStartLoadWithRequest:(*的NSURLRequest)reuqest navigationType:(UIWebViewNavigationType)navigationType;
//通过导航类型参数(navigationType)可以得到请求发起的原因,可以是以下任意值:
UIWebViewNavigationTypeLinkClicked
UIWebViewNavigationTypeFormSubmitted
UIWebViewNavigationTypeBackForward
UIWebViewNavigationTypeReload
UIWebViewNavigationTypeFormResubmitted
UIWebViewNavigationTypeOther
//当网页视图已经开始加载一个请求后,得到通知。
- (无效)webViewDidStartLoad:(UIWebView的*)web视图;
//当网页视图结束加载一个请求之后,得到通知。
- (无效)webViewDidFinishLoad:(UIWebView的*)web视图;
//当在请求加载中发生错误时,得到通知。会提供一个NSSError对象,以标识所发生错误类型。
- (无效)web视图:(UIWebView的*)web视图DidFailLoadWithError:(NSError *)错误;
[参考] http://blog.csdn.net/toss156/article/details/7303425
与JavaScript的的交互
stringByEvaluatingJavaScriptFromString方法可以将javascript嵌入页面中,通过这个方法我们可以在iOS中与UIWebView中的网页元素交互。
我们在webViewDidFinishLoad方法中就可以通过JavaScript的操作界面元素了。
获取当前页面的URL。
- (无效)webViewDidFinishLoad:(UIWebView的*){web视图
* NSString的CURRENTURL = [web视图stringByEvaluatingJavaScriptFromString:@“document.location.href”];
}
获取页面标题:
- (无效)webViewDidFinishLoad:(UIWebView的*){web视图
* NSString的CURRENTURL = [web视图stringByEvaluatingJavaScriptFromString:@“document.location.href”];
* NSString的标题=的WebView stringByEvaluatingJavaScriptFromString:@“document.title时”];
}
修改界面元素的值。
的NSString * js_result = [web视图stringByEvaluatingJavaScriptFromString:@“document.getElementsByName('Q')[0]。价值=”AAA“;”];
表单提交
* NSString的js_result2 = [web视图stringByEvaluatingJavaScriptFromString:@“document.forms [0] .submit();”];
插入JS代码
我们可以封装到一个JS函数中,将这个函数插入到页面上执行,代码如下:
- (无效)webViewDidFinishLoad:(UIWebView的*){web视图
//拦截网页图片并修改图片大小
[web视图stringByEvaluatingJavaScriptFromString:
@“VAR脚本=使用document.createElement('脚本');”
“script.type =”文/ JavaScript的“;”
“script.text = \”功能ResizeImages(){“
“VAR myimg,oldwidth;”
“VAR了maxWidth = 300;” //缩放系数
“对于(i = 0;我 <document.images.length;i++){" "myimg="document.images[i];"" "if(myimg.width=""> 了maxWidth){“
“oldwidth = myimg.width;”
“myimg.width =了maxWidth;”
//"myimg.height = myimg.height *(了maxWidth / oldwidth);“
“}”
“}”
“} \”;“
“document.getElementsByTagName('头')[0] .appendChild(脚本);”];
//
[web视图stringByEvaluatingJavaScriptFromString:@“ResizeImages();”];
}
[参考]http://www.cnblogs.com/zhuqil/archive/2011/08/03/2126562.html
响应图片长按事件
静态的NSString * const的kTouchJavaScriptString =
@“document.ontouchstart =函数(事件){\
X = event.targetTouches [0] .clientX; \
Y = event.targetTouches [0] .clientY; \
document.location = \“MyWeb即可:触摸:启动:\”+ X + \“:\”+ Y;};“;
- (无效)webViewDidFinishLoad:(UIWebView的*){web视图
[web视图stringByEvaluatingJavaScriptFromString:kTouchJavaScriptString];
}
//功能:UIWebView的响应长按事件
- (BOOL)web视图:(UIWebView的*)web视图shouldStartLoadWithRequest:(*的NSURLRequest)要求navigationType:(UIWebViewNavigationType)navigationType {
* NSString的requestString = [[URL请求] absoluteString]
NSArray的*组件= [requestString componentsSeparatedByString:@“”];
如果([组件数]> 1 && [(的NSString *)[成分objectAtIndex:0]
isEqualToString:@“MyWeb即可”]){
如果([(的NSString *)[成分objectAtIndex:1] isEqualToString:@“触摸”])
{
如果([(的NSString *)[成分objectAtIndex:2] isEqualToString:@“开始”])
{
/ *
@需延时判断是否响应页面内的JS ...
* /
self.gesState = GESTURE_STATE_START;
浮PTX = [[成分objectAtIndex:3]的floatValue]
浮PTY = [[成分objectAtIndex:4]的floatValue]
* NSString的JS = [的NSString stringWithFormat:@“document.elementFromPoint(%F,%F).tagName”,PTX,PTY]
* NSString的标签名= [self.webView stringByEvaluatingJavaScriptFromString:JS];
self.imgUrl =零;
如果([标签名isEqualToString:@“IMG”]){
self.imgUrl = [的NSString stringWithFormat:@“document.elementFromPoint(%F,%F)的.src”,PTX,PTY]
}
如果(self.imgUrl){
self.timer = [的NSTimer scheduledTimerWithTimeInterval:0.5目标:自我选择:@选择(handleLongTouch :)用户信息:无重复:NO];
}
}
}
返回NO;
}
返回YES;
}
//功能:如果点击的是图片,并且按住的时间超过1秒,执行handleLongTouch函数。
- (无效)handleLongTouch:(*的NSTimer)定时器{
如果(self.imgUrl && self.gesState == GESTURE_STATE_START){
self.gesState = GESTURE_STATE_END;
HomeDetailImageViewController * imageViewController = [[HomeDetailImageViewController的alloc]初始化];
imageViewController.imgUrlStr = [self.webView stringByEvaluatingJavaScriptFromString:self.imgUrl];
[self.navigationController pushViewController:imageViewController动画:是];
}
}
[参考] http://www.tuicool.com/articles/j6fmY3j
在UIWebView的内容加载完之后,可以利用javascript获取其页面内的数据,核心就是通过UIWebView的方法:
NSString *string = [awebView stringByEvaluatingJavaScriptFromString:@"document.getElementById('field_2').value;" ];
以下是一些常用的js脚本:
thisURL = document.URL;
thisHREF = document.location.href;
thisSLoc = self.location.href;
thisDLoc = document.location;
thisTLoc = top.location.href;
thisPLoc = parent.document.location;
thisTHost = top.location.hostname;
thisHost = location.hostname;
thisTitle = document.title;
thisProtocol = document.location.protocol;
thisPort = document.location.port;
thisHash = document.location.hash;
thisSearch = document.location.search;
thisPathname = document.location.pathname;
thisHtml = document.documentElement.innerHTML;
thisBodyText = document.documentElement.innerText;//获取网页内容文字
thisBodyText = document.body.innerText;//获取网页内容文字
也可以通过同样的方法去设置页面内容(比如帮用户输入表单数据)
比如:NSString *string = [awebView stringByEvaluatingJavaScriptFromString:@"document.getElementById('field_2').value='a value';" ];
就可以修改field_2的值了
同样也可以去模拟页面内按钮的点击,提交页面,比如:document.getElementById('aButtonName').click();
或者,假设知道按钮是第几个input标签(假设为第一个)document.getElementsByTagName('input').item(0).click();
也可以设置checkBox的状态:document.getElementById('aCheckBoxId').checked=true;
参考:
http://hi.baidu.com/zfpp25/blog/item/0bc5e3565a7e632e0cf3e3d7.html
http://www.cnblogs.com/del/archive/2009/01/07/1370907.html
http://blog.csdn.net/studyrecord/article/details/6213843
UIWebView与JS的交互的更多相关文章
- iOS中使用UIWebView与JS进行交互
iOS中使用UIWebView与JS进行交互 前一段忙着面试和复习,这两天终于考完试了,下学期的实习也有了着落,把最近学的东西更新一下,首先是使用UIWebView与JS进行交互 在webView中我 ...
- 【Swift】WKWebView与JS的交互使用
一.前言 近日,有朋友问我关于WKWebView与JS的交互问题,可我之前一直使用的是UIWebView,也不曾做过WKWebView的交互啊!接下来大家一块学习下WKWebView是怎么实现原生代码 ...
- 【iOS开发】UIWebView与JavaScript(JS) 回调交互
------------------------------------------------- 很多关于objc 与 js 交互的文章都比较适用于 mac开发,iOS的webview 还是有所不一 ...
- iOS UIWebView和网页的交互(OC中调执行JS)
UIWebView和网页的交互(OC中调执行JS)- (void)viewDidLoad{[super viewDidLoad];// 1.webViewUIWebView *webView = [[ ...
- UIWebView与JS的深度交互
我要实现这样一个需求:按照本地的CSS文件展示一串网络获取的带HTML格式的只有body部分的文本,需要自己拼写完整的 HTML.除此之外,还需要禁用获取的HTML文本中自带的 < img &g ...
- UIWebView与JS的深度交互-b
要实现这样一个需求:按照本地的CSS文件展示一串网络获取的带HTML格式的只有body部分的文本,需要自己拼写完整的 HTML.除此之外,还需要禁用获取的HTML文本中自带的 < img > ...
- UIWebView与JavaScript(JS) 回调交互 -备
很多关于objc 与 js 交互的文章都比较适用于 mac开发,iOS的webview 还是有所不一样, 参考:http://blog.sina.com.cn/s/blog_693de6100102v ...
- [转]OC与JS的交互详解
事情的起因还是因为项目需求驱动.折腾了两天,由于之前没有UIWebView与JS交互的经历,并且觉得这次在功能上有一定的创造性,特此留下一点文字,方便日后回顾. 我要实现这样一个需求:按照本地的CSS ...
- iOS中UIWebView执行JS代码(UIWebView)
iOS中UIWebView执行JS代码(UIWebView) 有时候iOS开发过程中使用 UIWebView 经常需要加载网页,但是网页中有很多明显的标记让人一眼就能看出来是加载的网页,而我们又不想被 ...
随机推荐
- Spring的jsp标签库
1,主要有两个 一个用于渲染HTML表单标签, 这些标签会绑定model中的某个属性 另一个包换了一些工具类标签 2,将表单绑定到模型上 包含了14个标签,海报一个人为用户展现错误的标签,它会将错误信 ...
- linux iconv文件编码转换
linux系统里提供的文件转化编码的命令iconv,例如: iconv -t utf-8 -f gb2312 -c test.xml > text_UTF8.xml 1 -f 源编码-t 目标编 ...
- shiro所需的依赖
<dependency> <groupId>org.apache.shiro</groupId> <artifactId>shiro-spring< ...
- ES6学习一--ES5
JSON对象方法 1.将JSON字符串转换成js对象(IE7及以下不支持)(IE7及以下兼容需其他手段) JSON.parse() 2.将js对象转成JSON字符串 JSON.stringify() ...
- C# base64 加密解密
1.base64 to string string strPath = "aHR0cDovLzIwMy44MS4yOS40Njo1NTU3L1 9iYWlkdS9yaW5ncy9taWR ...
- leetcode-easy-trees-108. Convert Sorted Array to Binary Search Tree
mycode 81.75 # Definition for a binary tree node. # class TreeNode(object): # def __init__(self, x) ...
- java操作poi生成excel.xlsx(设置下拉框)下载本地和前端下载
需求:导入excel表格,如果excel有错误,将错误的地方标红,在把数据以excel的形式写出,供用户下载解决方案:1.以实体类的方式接收excel并解析(创建两个集合一个接收正常的数据一个接收错误 ...
- java的引用传递
public class T{ static class Node{ int value; Node left = null; Node right = null; public Node(int v ...
- 算法 - DNA搜索 - Ako Corasick
场景:从很长的字符串(输入字符串.DNA)中搜索大量固定字符串(字典.基因) 题目:Determining DNA Health | HackerRank 算法:Aho–Corasick algori ...
- Android 中数据存储方式有哪些?
a) 文件存储b) xml,SharedPreferencec) SQLite数据库d) ContentProvidere) 网络