In iOS development, you sometimes use object and JavaScript to call each other, in the following steps:
1. The execution of JavaScript code in object, this is relatively simple, Apple provides a good way
-(nsstring *) stringbyevaluatingjavascriptfromstring: (nsstring *) script
2. The data returned to object during JavaScript execution or the object method is called
The UIWebView address redirection function, the main code is as follows:
(1) Create 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) RealizeUIWebView 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 excuteJa Vascript];} -(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];}
The description is as follows:
(1) When UIWebView loading the Web page, that is, when executing to the Webviewdidfinishload agent, execute a piece of JavaScript code, the function of this code is to get the video address in the Web page, the code "Document.location = ' Myvideo ' + video.getattribute (' src '); "This is especially important,document.location is for address redirection, executes the JavaScript code, and then executes
-(BOOL) WebView: (uiwebview *) WebView shouldstartloadwithrequest: (nsurlrequest *) Request Navigationtype: (uiwebviewnavigationtype) Navigationtype This proxy method, which captures the address given by Document.location as ' Myvideo ' + video.getattribute (' src ');. You can get rid of the ' Myvideo ' head, you can obtain what you need, where ' Myvideo ' is your own definition of a head, is to facilitate the analysis of the subsequent data.
IOS object and JavaScript call each other