技术iOS吧iOS - WebView

iOS webView与JS的交互(干货)

2017-05-10  本文已影响4957人  酒深巷子Ya

一、webView加载html代码

webVidew的方法
- (nullable NSString *)stringByEvaluatingJavaScriptFromString:(NSString *)script;

二、对webView内的链接进行限制

- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType

{
NSString *url = request.URL.absoluteString;  
if ([url rangeOfString:@
"[hiya://](hiya://)"
].location != NSNotFound) { 
// url的协议头是hiya  
NSLog(@
"hd1009"
);     
return
 NO;
}
return YES;
}

捕获JS里面的方法(倒入JavaScriptCored框架)

- (void)webViewDidFinishLoad:(UIWebView *)webView
{
    JSContext *context = [webView valueForKeyPath:@"documentView.webView.mainFrame.javaScriptContext"];
    //定义好JS要调用的方法,finish就是调用的方法名
    context[@"finish"] = ^() {
        dispatch_async(dispatch_get_main_queue(), ^{
            UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"方式二" message:@"这是OC原生的弹出窗" delegate:self cancelButtonTitle:@"收到" otherButtonTitles:nil];
            [alertView show];
        });
    };
}

三、获取页面内的任意标签属性的值

- (void)webViewDidFinishLoad:(UIWebView *)webView{
    
    NSString *title = [webView stringByEvaluatingJavaScriptFromString:@"document.title"];//获取当前页面的title
NSString *html = @"document.documentElement.innerHTML";//获取当前网页的html
NSString *html2 = [webView stringByEvaluatingJavaScriptFromString:@"document.getElementById('creditNum').innerText"];//获取id为creditNum标签的值
NSString *html3 = [webView stringByEvaluatingJavaScriptFromString:@"document.getElementById('zmScore').value"];//获取标签为id为zmScore的value
NSString *html2 = [webView stringByEvaluatingJavaScriptFromString:@"document.getElementsByTagName('p')[0].innerText"];//获取标签第一个p的值
NSString *html2 = [webView stringByEvaluatingJavaScriptFromString:@"document.body.innerText"];//获取body里面的全部内容
}

附html代码如下:

<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8">
        <title>1234</title>
    </head>
    <style type="text/css">
        .issue{
            font-family: "微软雅黑";
            font-size: 1.2em;
            font-weight: 900;
        }
        .answer{
            font-family: "微软雅黑";
            font-size: 1em;
            margin-top:-15px;
        }
    </style>
    <body>
        <input type='hidden' id='zmScore' value='719'/><input type='hidden' id='freeDeposit' value='true'/>
        <p id="creditNum"> 791 </P>
        <p class="issue">Q:什么是骑行券?</p>
        <p class="answer">A:骑行费用的电子券。</p>
        
        <p class="issue">Q:如何获得骑行券?</p>
        <p class="answer">A:关注运营方举办的活动。</p>
        
        <p class="issue">Q:如何使用骑行券?</p>
        <p class="answer">A:无需用户手动选择。</p>
        
        <p class="issue">Q:一次骑行能有几张骑行券?</p>
        <p class="answer">A:每次骑行结算只能使用一张骑行券。</p>
        
    </body>
</html>

持续更新中 ~ (🙈)

上一篇 下一篇

猜你喜欢

热点阅读