oc 和 h5中js 的交互

来源:互联网 发布:数据库应用系统饭店 编辑:程序博客网 时间:2024/06/10 01:32

最近项目中要用到html5来实现,涉及到OC调用JS,以及JS调用OC的方法,这里把遇到的问题以及实现方法介绍一下。


[objc] view plain copy
  1. //  
  2. //  ViewController.h  
  3. //  OC_And_JS  
  4. //  
  5. //  Created by 张杰 on 15/7/9.  
  6. //  Copyright © 2015年 张杰. All rights reserved.  
  7. //  
  8.   
  9. #import <UIKit/UIKit.h>  
  10.   
  11. @interface ViewController : UIViewController <UIWebViewDelegate>  
  12.   
  13. @property (weak, nonatomic) IBOutlet UIButton *oc_call_js_no_params;  
  14. @property (weak, nonatomic) IBOutlet UIButton *oc_call_js_has_params;  
  15. @property (weak, nonatomic) IBOutlet UIWebView *mWebView;  
  16. @property (weak, nonatomic) IBOutlet UILabel *js_call_oc_show;  
  17.   
  18. - (IBAction)ocCallJsNoParams:(id)sender;  
  19. - (IBAction)ocCallJsHasParams:(id)sender;  
  20.   
  21.   
  22. @end  


[objc] view plain copy
  1. //  
  2. //  ViewController.m  
  3. //  OC_And_JS  
  4. //  
  5. //  Created by 张杰 on 15/7/9.  
  6. //  Copyright © 2015年 张杰. All rights reserved.  
  7. //  
  8.   
  9. #import "ViewController.h"  
  10.   
  11. @interface ViewController ()  
  12.   
  13. @end  
  14.   
  15. @implementation ViewController  
  16.   
  17. - (void)viewDidLoad {  
  18.     [super viewDidLoad];  
  19.     _mWebView.delegate = self;  
  20.       
  21.     //打开URL  
  22.     NSString *path = [[NSBundle mainBundle] pathForResource:@"index" ofType:@"html"];  
  23.     [self.mWebView loadRequest:[NSURLRequest requestWithURL:[NSURL fileURLWithPath: path]]];  
  24. }  
  25.   
  26. - (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType{  
  27.     NSString *urlstr = request.URL.absoluteString;  
  28.     NSRange range = [urlstr rangeOfString:@"ios://jwzhangjie"];  
  29.     if (range.length!=0) {  
  30.         _js_call_oc_show.text = [NSString stringWithFormat:@"请访问地址:%@", urlstr];  
  31.     }  
  32.     return YES;  
  33. }  
  34.   
  35. -(void)webView:(nonnull UIWebView *)webView didFailLoadWithError:(nullable NSError *)error{  
  36.     NSLog(@"加载失败");  
  37. }  
  38.   
  39. -(void)webViewDidStartLoad:(nonnull UIWebView *)webView{  
  40.     NSLog(@"开始加载");  
  41. }  
  42.   
  43.   
  44. -(void)webViewDidFinishLoad:(nonnull UIWebView *)webView{  
  45.     NSLog(@"开始结束");  
  46. //    对于调用js的时候最好这个方法里面或者之后  
  47. }  
  48.   
  49.   
  50. - (void)didReceiveMemoryWarning {  
  51.     [super didReceiveMemoryWarning];  
  52.     // Dispose of any resources that can be recreated.  
  53. }  
  54.   
  55.   
  56.   
  57. - (IBAction)ocCallJsNoParams:(id)sender {  
  58.     NSString *js = [NSString stringWithFormat:@"ocCallJsNoParamsFunction();"];  
  59.     [self.mWebView stringByEvaluatingJavaScriptFromString:js];  
  60. }  
  61.   
  62. - (IBAction)ocCallJsHasParams:(id)sender {  
  63.     NSString *js = [NSString stringWithFormat:@"ocCallJsHasParamsFunction('%@','%@');",@"jwzhangjie",@"http://jwzhangjie.cn"];  
  64.     [self.mWebView stringByEvaluatingJavaScriptFromString:js];  
  65. }  
  66. @end  

[javascript] view plain copy
  1. function ocCallJsNoParamsFunction()  
  2. {  
  3.     alert("OC调用JS中的无参方法");  
  4.     var e = document.getElementById("js_shouw_text");  
  5.     e.options.add(new Option("OC调用JS中的无参方法", 2));  
  6. }  
  7.   
  8. function ocCallJsHasParamsFunction(name, url)  
  9. {  
  10.     alert(name+"的博客地址为:"+url);  
  11.     var e = document.getElementById("js_shouw_text");  
  12.     e.options.add(new Option("OC调用JS中的有参方法", 2));  
  13. }  

[html] view plain copy
  1. <!DOCTYPE html>  
  2. <html lang="zh-CN">  
  3. <head>  
  4.     <meta charset="utf-8">  
  5.     <title>OC与JS互相调用</title>  
  6. </head>  
  7. <body>  
  8.     <div >  
  9.         <select id="js_shouw_text">  
  10.             <option>  
  11.                 展示OC调用JS无参数  
  12.             </option>  
  13.         </select>  
  14.     </div>  
  15.     <div>  
  16.         <BR/>  
  17.         <input type="button" value="JS调用OC方法" onclick="js_call_oc()"/>  
  18.     </div>  
  19.     <!--  这里要清楚,虽然test.js跟index.html不同及目录,实际安装到程序里面后,是在同级目录的,所以这里src不能加目录,同样css也是一样的  -->  
  20.     <script type="text/javascript" src="test.js" charset="UTF-8"></script>  
  21.     <script type="text/javascript">  
  22.         function js_call_oc()  
  23.         {  
  24.             var iFrame;  
  25.             iFrame = document.createElement("iframe");  
  26.             iFrame.setAttribute("src", "ios://jwzhangjie");  
  27.             iFrame.setAttribute("style", "display:none;");  
  28.             iFrame.setAttribute("height", "0px");  
  29.             iFrame.setAttribute("width", "0px");  
  30.             iFrame.setAttribute("frameborder", "0");  
  31.             document.body.appendChild(iFrame);  
  32.             // 发起请求后这个iFrame就没用了,所以把它从dom上移除掉  
  33.             iFrame.parentNode.removeChild(iFrame);  
  34.             iFrame = null;  
  35.         }  
  36.           
  37.     </script>  
  38. </body>  
  39.   
  40. </html>  

规避1:对于OC去调用JS内容最好在webViewDidFinishLoad方法里或者之后

规避2:在html里面引用js或者css的时候src不要带有路径,因为安装后文件都在同级目录下面

规避3:OC调用JS的规范

[objc] view plain copy
  1. NSString *js = [NSString stringWithFormat:@"ocCallJsHasParamsFunction('%@','%@');",@"jwzhangjie",@"http://jwzhangjie.cn"];  
  2.    [self.mWebView stringByEvaluatingJavaScriptFromString:js];  
规避4:JS调用OC,这里通过html里面发送一个请求,然后在ios中使用shouldStartLoadWithRequest拦截请求,根据请求url的不同进行处理。

[javascript] view plain copy
  1. function js_call_oc()  
  2.        {  
  3.            var iFrame;  
  4.            iFrame = document.createElement("iframe");  
  5.            iFrame.setAttribute("src""ios://jwzhangjie");  
  6.            iFrame.setAttribute("style""display:none;");  
  7.            iFrame.setAttribute("height""0px");  
  8.            iFrame.setAttribute("width""0px");  
  9.            iFrame.setAttribute("frameborder""0");  
  10.            document.body.appendChild(iFrame);  
  11.            // 发起请求后这个iFrame就没用了,所以把它从dom上移除掉  
  12.            iFrame.parentNode.removeChild(iFrame);  
  13.            iFrame = null;  
  14.        }  

[objc] view plain copy
  1. - (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType{  
  2.     NSString *urlstr = request.URL.absoluteString;  
  3.     NSRange range = [urlstr rangeOfString:@"ios://jwzhangjie"];  
  4.     if (range.length!=0) {  
  5.         _js_call_oc_show.text = [NSString stringWithFormat:@"请访问地址:%@", urlstr];  
  6.     }  
  7.     return YES;  
  8. }  

源码地址:

http://jwzhangjie.cn/forum.php?mod=viewthread&tid=3&page=1&extra=#pid3

0 0