In IOS development, objects and javaScript are sometimes used to call each other. The specific steps are as follows:
1. execute javascript code in the Object. This is relatively simple. Apple provides a good method.
-(NSString *) stringByEvaluatingJavaScriptFromString :( NSString *) script
2. The data returned to the Object during javascript execution or the Object method is called.
The main code of the address redirection function of UIWebView is as follows:
(1) create a 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) Implement the UIWebView Method
#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];}
Description:
(1) When the UIWebView loads the webpage, it executes a javascript code when the webViewDidFinishLoad proxy is executed. The purpose of this Code is to obtain the video address in the webpage, in which "document. location = 'myvideo' + video. getAttribute ('src'); "This section is particularly important, document. location is used for address redirection. After the javascript code is executed
-(BOOL) webView :( UIWebView *) webView shouldStartLoadWithRequest :( NSURLRequest *) request navigationType :( UIWebViewNavigationType) The navigationType proxy method will capture the document. the address given by location is 'myvideo' + video. getAttribute ('src ');. You can remove the 'myvideo' header to get what you need. 'myvideo' is a custom header to facilitate data parsing.