IOS Object和javaScript相互调用

Posted brucemengbm

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了IOS Object和javaScript相互调用相关的知识,希望对你有一定的参考价值。

ios开发中有时会用到Object和javascript相互调用,详细过程例如以下:

1. Object中运行javascript代码,这个比較简单,苹果提供了非常好的方法

- (NSString *)stringByEvaluatingJavaScriptFromString:(NSString *)script

2. javascript运行过程中返回给Object的数据或者调用Object方法。这个时候就须要用到

UIWebView的地址重定向功能。主要代码例如以下:

(1)创建UIWebView

    webView = [[UIWebView alloc] initWithFrame:self.view.bounds];
    webView.delegate = self;
    [self.view addSubview:webView];
    [self loadWebPageWithString:_url];

- (void)loadWebPageWithString:(NSString*)urlString
{
    NSURL *url =[NSURL URLWithString:urlString];
    NSURLRequest *request =[NSURLRequest requestWithURL:url];
    [webView loadRequest:request];
}


(2)实现UIWebView方法

#pragma mark - UIWebViewDelegate
- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType
{
    NSString *urlString = [[request URL] absoluteString];
    debuglog(@"urlString = %@",urlString);
    NSString *prefix = @"myvideo";
    if ([urlString hasPrefix:prefix]) {
        NSString *endString = [urlString substringFromIndex:7];
        debuglog(@"last urlString = %@",endString);
        
        return NO;
    }

    return YES;
}

- (void)webViewDidStartLoad:(UIWebView *)webView
{
    
}

- (void)webViewDidFinishLoad:(UIWebView *)webView
{
    [self excuteJavaScript];
}

- (void)webView:(UIWebView *)webView didFailLoadWithError:(NSError *)error
{
    
}

- (void)excuteJavaScript
{
    NSString *js = @"var video =  document.getElementsByTagName(‘video‘)[0];setTimeout(getVideo,1000); function getVideo(){ video =  document.getElementsByTagName(‘video‘)[0];if(video==undefined){setTimeout(getVideo,1000);}else{ video.pause();if(video.src==‘‘){var video = document.getElementsByTagName(‘source‘)[0];}document.location = ‘myvideo‘+ video.getAttribute(‘src‘);injectedObject.playVideo(video.getAttribute(‘src‘));}}";

    [webView stringByEvaluatingJavaScriptFromString:js];
}

说明例如以下:

(1)在UIWebView载入完网页的时候,即运行到webViewDidFinishLoad代理的时候。运行一段javascript代码。这段代码的作用是获取网页中的视频地址,代码中“ document.location = ‘myvideo‘+ video.getAttribute(‘src‘); ”这段特别重要,document.location是为了做地址重定向用的,运行完这段javascript代码。接着就会运行

- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType 这个代理方法,当中就会捕获到document.location给出的地址即‘myvideo‘+ video.getAttribute(‘src‘); 。你能够去掉‘myvideo‘头。就能够得到你须要的东西了。当中‘myvideo‘是你自定义的一个头。是为了便于解析后面的数据。














以上是关于IOS Object和javaScript相互调用的主要内容,如果未能解决你的问题,请参考以下文章

iOS js oc相互调用(JavaScriptCore)

转载 iOS js oc相互调用(JavaScriptCore)

iOS js oc相互调用JavaScriptCore

iOS js oc相互调用(JavaScriptCore)

Android Webview 和Javascript交互,实现Android和JavaScript相互调用

iOS中Objective-C与JavaScript之间相互调用的实现(实现了与Android相同的机制)