webview 与 js交互

本文介绍了一种使用JavaScript与iOS中的UIWebView进行交互的方法。主要包括如何将JavaScript代码注入到WebView中,以及如何通过重定向机制实现两者之间的消息传递。此外还提供了一些关于中文乱码处理的技巧。

本来在看cocos2d,今天分了一个和 js有关的活,查了和测试些资料整理下

源码下载:http://download.youkuaiyun.com/detail/worn_nest/4845878

嘿,挣点分好下别人的


1.test.js

function sendCommand(cmd,param){
    var url="testapp:"+cmd+":"+param;
    document.location = url;
}
function clickLink(){
    sendCommand("alert","你好吗?");
}

2. htmlTest.html

<html>
<body>

<input type="button" value="Click me!" onclick="clickLink()" /><br/>  

</body>
</html>

3.js 与 webview交互

- (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交互
     */
}

/*
 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.备注一些问题

加载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







                
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值