项目介绍:
JS与OC的交互,修改、添加、删除h5页面内容
主要代码:
[Objective-C] 查看源文件 复制代码
#pragma UIWebViewDelegate方法 - (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType{ NSLog(@"开始响应请求时触发"); return YES; } - (void)webViewDidStartLoad:(UIWebView *)webView{ NSLog(@"开始加载网页"); } // UIWebViewDelegate - (void)webViewDidFinishLoad:(UIWebView *)webView{ NSLog(@"网页加载完毕"); /* <p class="myimg"> <img src="http://p1.ifengimg.com/a/2016_24/be65927e27de090_size57_w530_h318.jpg" width="312" height="312" alt > </p> --------1.获取id为‘myimg’的p标签,然后删除----------------- // */ // NSString *str1 = @"var p = document.getElementById('myimg');"; // NSString *str2 = @"p.remove();"; // [webView stringByEvaluatingJavaScriptFromString:str1]; // [webView stringByEvaluatingJavaScriptFromString:str2]; //-------2.更改 修改<li class = "shouye">首页</li>列表标签的内容----------------- NSString *str3 = @"var zzz = document.getElementsByClassName('shouye')[0];""zzz.innerHTML = '你是猪吗??';"; [webView stringByEvaluatingJavaScriptFromString:str3]; //-------3.插入 图片---------------------------------- NSString *str4 = @"var img = document.createElement('player');" "img.src = 'http://yuntv.letv.com/player/live/blive.js';" "img.width = '320';" "img.height = '180';" "img = new CloudLivePlayer();" "img.init =({activityId:'A2016080300000in'});" "document.body.appendChild(img);"; /* 前面 "var first=document.body.firstChild;" "document.body.insertBefore(img,first);" */ [webView stringByEvaluatingJavaScriptFromString:str4]; // 拼接一个脚本语言中的 自动定位代码 /* <div id="player" style="width:100%;height:450px;"> <script type="text/javascript" charset="utf-8" src="http://yuntv.letv.com/player/live/blive.js"></script> <script> var player = new CloudLivePlayer(); player.init({activityId:"A2016080300000in"}); </script> </div> <div id="player" style="width:100%;height:450px;"> <script type="text/javascript" charset="utf-8" src="http://yuntv.letv.com/player/live/blive.js"></script> <script> var player = new CloudLivePlayer(); player.init({activityId:"A2016080900000hj"}); </script> </div> */ //-------4.js中给标签添加相印事件------------------- NSString *str5 = @"var baidu = document.getElementsByTagName('a')[0];" // NSString *str5 = @"var baidu = document.getElementById('dsd');" "baidu.innerHTML = '你是猪a ??';" "baidu.onclick = function(){alert('点我点我点我')};"; [webView stringByEvaluatingJavaScriptFromString:str5]; //-------5js调用oc---------------------------- //JSContext * context; //获取js的运行环境 _context=[webView valueForKeyPath:@"documentView.webView.mainFrame.javaScriptContext"]; //html调用无参数OC _context[@"test1"] = ^(){ [self menthod1]; }; //html调用OC(传参数过来) _context[@"test2"] = ^(){ NSArray * args = [JSContext currentArguments];//传过来的参数 // for (id obj in args) { // NSLog(@"html传过来的参数%@",obj); // } NSString * name = args[0]; NSString * str = args[1]; [self menthod2:name and:str]; }; }
oc与js的爱恋.zip
(352.17 KB, 下载次数: 628)
2016-8-10 15:54 上传
点击文件名下载附件
简单使用