UIWebView JS简单交互

来源:互联网 发布:矩阵等价和相等的区别 编辑:程序博客网 时间:2024/05/22 03:05

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 onclick="getInfo('name')">name</h3><p id="name"></p></div><div data-role="collapsible"><h3 onclick="getInfo('systemVersion')">systemVersion</h3><p id="systemVersion"></p></div></div></div></div></body></html>





0 0
原创粉丝点击