iOS 之webView与js交互

本文介绍了一种使用JavaScript与iOS中的UIWebView进行交互的方法。主要包括如何将JavaScript代码注入到UIWebView中,以及如何通过重定向请求来实现两者之间的数据传递。此外还提供了处理中文乱码及不同方式加载HTML页面的技巧。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

本文来自:http://blog.youkuaiyun.com/worn_nest/article/details/8256913


本来在看cocos2d,今天分了一个和 js有关的活,查了和测试些资料整理下
源码下载:http://download.youkuaiyun.com/detail/worn_nest/4845878
嘿,挣点分好下别人的


1.test.js
[html] view plaincopyprint?
function sendCommand(cmd,param){  
    var url="testapp:"+cmd+":"+param;  
    document.location = url;  
}  
function clickLink(){  
    sendCommand("alert","你好吗?");  
}  


2. htmlTest.html
[html] view plaincopyprint?
<html>  
<body>  
  
<input type="button" value="Click me!" onclick="clickLink()" /><br/>    
  
</body>  
</html>  


3.js 与 webview交互
[cpp] view plaincopyprint?
- (void)viewDidLoad  
{  
    [super viewDidLoad];  
    self.web = [[[UIWebView alloc] initWithFrame:self.view.bounds] autorelease];  
      
#if 0  
    // 网络html  
    NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:@"http://www.baidu.com"]];  
#else  
    // 本地html  
    NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"htmlTest" ofType:@"html"]]];  
#endif  
    [web loadRequest:request];  
    web.delegate = self;  
    [self.view addSubview:web];  
      
      
      
    /* 
     - step 1 
     - 注入js 
     */  
    NSString *p = [[NSBundle mainBundle] pathForResource:@"test" ofType:@"js"];  
    NSString *js = [NSString stringWithContentsOfFile:p encoding:NSUTF8StringEncoding error:nil];  
    [web stringByEvaluatingJavaScriptFromString:js];  
      
      
    /* 
     - step 2 
     - 调用方法 
      
     1.直接调用 
       [web stringByEvaluatingJavaScriptFromString:@"clickLink();"]; 
     2.通过重定向实现js 与 webview交互 
     */  
}  


[cpp] view plaincopyprint?
/* 
 webview 与 js交互: 
 - 利用UIWebView重定向请求 
 - 1.编写test.js方法 
 - 2.注入本地html 
 - 3.重定向交互 
 */  
- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType {  
  
    NSString *requestString = [[request URL] absoluteString];  
      
    // 中文乱码转换  
    NSLog(@"pre:%@",requestString);// pre:testapp:alert:%E4%BD%A0%E5%A5%BD%E5%90%97%EF%BC%9F  
    requestString = [requestString stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];  
    NSLog(@"cov:%@",requestString);// cov:testapp:alert:你好吗?  
      
  
    NSArray *components = [requestString componentsSeparatedByString:@":"];  
    if ([components count] > 1 && [(NSString *)[components objectAtIndex:0] isEqualToString:@"testapp"]) {  
        if([(NSString *)[components objectAtIndex:1] isEqualToString:@"alert"])  
        {  
            UIAlertView *alert = [[UIAlertView alloc]  
                                  initWithTitle:@"alert from html" message:[components objectAtIndex:2]  
                                  delegate:self cancelButtonTitle:nil  
                                  otherButtonTitles:@"OK", nil];  
            [alert show];  
        }  
        return NO;  
    }  
    return YES;  
}  


4.备注一些问题
[cpp] view plaincopyprint?
加载html三种方法  
//1.加载网络html  
NSURL *url = [NSURL URLWithString:@"http://localhost:8080/jmDemo/index.html"];    
NSURLRequest *request = [NSURLRequest requestWithURL:url];    
[_webView loadRequest:request];   
  
//2.加载资源中html  
NSString *path = [[NSBundle mainBundle] pathForResource:@"indedx" ofType:@"html"];    
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL fileURLWithPath:path]];    
[_webView loadRequest:request];    
  
//3.加载doc中html  
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);    
NSString *documentsDirectory = [paths objectAtIndex:0];    
NSString *path = [documentsDirectory stringByAppendingPathComponent:@"index.html"];    
NSURL *url = [NSURL fileURLWithPath:path];    
NSURLRequest *request = [NSURLRequest requestWithURL:url];    
[_webView loadRequest:request];    
  
  
--------------------  
//中文乱码  
   
 //NSData 转 NSString  
 NSData *data;  
 NSString*str = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];  
   
 //NSString  转 NSData  
 NSString *string;  
 NSData*data = [string dataUsingEncoding:NSUTF8StringEncoding allowLossyConversion:YES];  
   
   
 //char 转 NSString  
 char *str1;  
 NSString*str = [NSString stringWithCString:str1 encoding:NSUTF8StringEncoding];  
   
 //NSString 转 char  
 NSString *str;  
 char *str1 = [str UTF8String];  
   
 //自转换  
 NSString*string;  
 string = [string stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];  




5.相关
开源工程大家可以看看,它允许javascript调用objective_c的方法。
http://code.google.com/p/jsbridge-to-cocoa/
还有两个相关工程
WebViewJavascriptBridge 与 GAJavaScript 值得大家慢慢研究。


参考:http://blog.youkuaiyun.com/favormm/article/details/6603923


[html] view plaincopyprint?
  
[html] view plaincopyprint?
<pre name="code" class="html"><pre></pre>  
<pre></pre>  
<pre></pre>  
<pre></pre>  
<pre></pre>  
  
</pre> 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值