uiwebview与js交互

1、UIWebView的 stringByEvaluatingJavaScriptFromString方法

2、UIWebViewDelegate的

- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest*)request navigationType:(UIWebViewNavigationType)navigationType方法

代码实例

1)加载页面

- (void)viewDidLoad
{
    [super viewDidLoad];
    NSString *path = [[NSBundle mainBundle] pathForResource:@"jm/info" ofType:@"html"];
    NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL fileURLWithPath:path]];
    [self.webView loadRequest:request];
}

2)设置委托-接收js请求并回调js方法

#pragma mark - UIWebViewDelegate

- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType
{
    if([request.mainDocumentURL.relativePath isEqualToString:@"/getInfo/name"])
    {
        NSString *info = [[UIDevice currentDevice] name];
        NSString *js = [NSString stringWithFormat:@"showInfo(\"name\",\"%@\")",info];
        [self.webView stringByEvaluatingJavaScriptFromString:js];
        return false;
    }
    if([request.mainDocumentURL.relativePath isEqualToString:@"/getInfo/systemVersion"])
    {
        NSString *info = [[UIDevice currentDevice] systemVersion];
        NSString *js = [NSString stringWithFormat:@"showInfo(\"systemVersion\",\"%@\")",info];
        [self.webView stringByEvaluatingJavaScriptFromString:js];
        return false;
    }
    return true;
}

3)JS代码

<!DOCTYPE html>
<html>
<head>
<title>city</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="jquery.mobile-1.0.css"/>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript" src="jquery.mobile-1.0.js"></script>
<script>
function getInfo(name)
{
window.location = "/getInfo/"+name;
}
function showInfo(id,info)
{
$("p#"+id).html(info);
}
</script>
</head>
<body>
<div data-role="page">
<div data-role="content">
<h2>Divice Info</h2>
<div data-role="collapsible-set" data-theme="c" data-content-theme="d">
<div data-role="collapsible">
<h3 οnclick="getInfo('name')">name</h3>
<p id="name"></p>
</div>
<div data-role="collapsible">
<h3 οnclick="getInfo('systemVersion')">systemVersion</h3>
<p id="systemVersion"></p>
</div>
</div>
</div>
</div>
</body>
</html>

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值