webview 与 js交互

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

源码下载:http://download.csdn.net/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!" οnclick="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.csdn.net/favormm/article/details/6603923







  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
在 Android 中,WebView 是一个内置的浏览器控件,可以加载网页并在应用程序中显示。WebView 与 JavaScript 的交互是常见的需求,主要有以下几种方式: 1. 通过 WebView 中的 loadUrl() 方法调用 JavaScript 函数。 可以使用 WebView 的 loadUrl() 方法加载一个包含 JavaScript 代码的 URL,实现与 JavaScript 的交互。例如,在 JavaScript 中定义一个函数: ```javascript function showToast(message) { alert(message); } ``` 然后在 Android 中使用 loadUrl() 方法调用这个函数: ```java webView.loadUrl("javascript:showToast('Hello World!')"); ``` 2. 在 WebView 中启用 JavaScript,并使用 addJavascriptInterface() 方法将 Java 对象注入到 JavaScript 中。 可以在 WebView 中启用 JavaScript 支持,并使用 addJavascriptInterface() 方法将 Java 对象注入到 JavaScript 中。这样,JavaScript 就可以调用 Java 对象的方法。例如,在 Java 中定义一个类: ```java public class MyJavaScriptInterface { private Context context; public MyJavaScriptInterface(Context context) { this.context = context; } @JavascriptInterface public void showToast(String message) { Toast.makeText(context, message, Toast.LENGTH_SHORT).show(); } } ``` 然后在 WebView 中启用 JavaScript 支持,并将 MyJavaScriptInterface 对象注入到 JavaScript 中: ```java webView.getSettings().setJavaScriptEnabled(true); webView.addJavascriptInterface(new MyJavaScriptInterface(this), "Android"); ``` 在 JavaScript 中就可以调用 MyJavaScriptInterface 对象的 showToast() 方法: ```javascript Android.showToast("Hello World!"); ``` 3. 使用 evaluateJavascript() 方法执行 JavaScript 代码并获取返回值。 可以使用 WebView 的 evaluateJavascript() 方法执行 JavaScript 代码,并通过回调函数获取返回值。例如,在 JavaScript 中定义一个函数: ```javascript function add(a, b) { return a + b; } ``` 然后在 Android 中使用 evaluateJavascript() 方法执行这个函数,并获取返回值: ```java webView.evaluateJavascript("add(1, 2)", new ValueCallback<String>() { @Override public void onReceiveValue(String value) { // value = "3" } }); ``` 以上就是 WebView 与 JavaScript 的交互方式,开发者可以根据需求选择适合自己的方式。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值